source: binary-improvements2/WebServer/src/WebUtils.cs@ 400

Last change on this file since 400 was 394, checked in by alloc, 2 years ago

SessionHandler cleanup + redirect to /app/error/:code
Some profiler usage cleanup

File size: 1.8 KB
Line 
1using System;
2using System.Net;
3using System.Text;
4using AllocsFixes.JSON;
5using HttpListenerRequest = SpaceWizards.HttpListener.HttpListenerRequest;
6using HttpListenerResponse = SpaceWizards.HttpListener.HttpListenerResponse;
7
8namespace Webserver {
9 public static class WebUtils {
10 public const string MimePlain = "text/plain";
11 public const string MimeHtml = "text/html";
12 public const string MimeJson = "application/json";
13
14 private static readonly UnityEngine.Profiling.CustomSampler jsonSerializeSampler = UnityEngine.Profiling.CustomSampler.Create ("JSON_Serialize");
15 private static readonly UnityEngine.Profiling.CustomSampler netWriteSampler = UnityEngine.Profiling.CustomSampler.Create ("JSON_Write");
16
17 public static void WriteJson (HttpListenerResponse _resp, JsonNode _root, HttpStatusCode _statusCode = HttpStatusCode.OK) {
18 jsonSerializeSampler.Begin ();
19 StringBuilder sb = new StringBuilder ();
20 _root.ToString (sb);
21 jsonSerializeSampler.End ();
22 netWriteSampler.Begin ();
23 WriteText (_resp, sb.ToString(), _statusCode, MimeJson);
24 netWriteSampler.End ();
25 }
26
27 public static void WriteText (HttpListenerResponse _resp, string _text, HttpStatusCode _statusCode = HttpStatusCode.OK, string _mimeType = null) {
28 _resp.StatusCode = (int)_statusCode;
29 _resp.ContentType = _mimeType ?? MimePlain;
30 _resp.ContentEncoding = Encoding.UTF8;
31
32 byte[] buf = Encoding.UTF8.GetBytes (_text);
33 _resp.ContentLength64 = buf.Length;
34 _resp.OutputStream.Write (buf, 0, buf.Length);
35 }
36
37 public static bool IsSslRedirected (HttpListenerRequest _req) {
38 string proto = _req.Headers ["X-Forwarded-Proto"];
39 return !string.IsNullOrEmpty (proto) && proto.Equals ("https", StringComparison.OrdinalIgnoreCase);
40 }
41
42 public static string GenerateGuid () {
43 return Guid.NewGuid ().ToString ();
44 }
45 }
46}
Note: See TracBrowser for help on using the repository browser.