source: binary-improvements2/MapRendering/Web/WebUtils.cs@ 388

Last change on this file since 388 was 387, checked in by alloc, 2 years ago

Big refactoring in Web to pass around a Context instead of a bunch of individual arguments all the time

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