1 | using System;
|
---|
2 | using System.Net;
|
---|
3 | using System.Text;
|
---|
4 | using AllocsFixes.JSON;
|
---|
5 | using HttpListenerRequest = SpaceWizards.HttpListener.HttpListenerRequest;
|
---|
6 | using HttpListenerResponse = SpaceWizards.HttpListener.HttpListenerResponse;
|
---|
7 |
|
---|
8 | namespace 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 | #if ENABLE_PROFILER
|
---|
15 | private static readonly UnityEngine.Profiling.CustomSampler jsonSerializeSampler = UnityEngine.Profiling.CustomSampler.Create ("JSON_Serialize");
|
---|
16 | private static readonly UnityEngine.Profiling.CustomSampler netWriteSampler = UnityEngine.Profiling.CustomSampler.Create ("JSON_Write");
|
---|
17 | #endif
|
---|
18 |
|
---|
19 | public static void WriteJson (HttpListenerResponse _resp, JsonNode _root, HttpStatusCode _statusCode = HttpStatusCode.OK) {
|
---|
20 | #if ENABLE_PROFILER
|
---|
21 | jsonSerializeSampler.Begin ();
|
---|
22 | #endif
|
---|
23 | StringBuilder sb = new StringBuilder ();
|
---|
24 | _root.ToString (sb);
|
---|
25 | #if ENABLE_PROFILER
|
---|
26 | jsonSerializeSampler.End ();
|
---|
27 | netWriteSampler.Begin ();
|
---|
28 | #endif
|
---|
29 | WriteText (_resp, sb.ToString(), _statusCode, MimeJson);
|
---|
30 | #if ENABLE_PROFILER
|
---|
31 | netWriteSampler.End ();
|
---|
32 | #endif
|
---|
33 | }
|
---|
34 |
|
---|
35 | public static void WriteText (HttpListenerResponse _resp, string _text, HttpStatusCode _statusCode = HttpStatusCode.OK, string _mimeType = null) {
|
---|
36 | _resp.StatusCode = (int)_statusCode;
|
---|
37 | _resp.ContentType = _mimeType ?? MimePlain;
|
---|
38 | _resp.ContentEncoding = Encoding.UTF8;
|
---|
39 |
|
---|
40 | byte[] buf = Encoding.UTF8.GetBytes (_text);
|
---|
41 | _resp.ContentLength64 = buf.Length;
|
---|
42 | _resp.OutputStream.Write (buf, 0, buf.Length);
|
---|
43 | }
|
---|
44 |
|
---|
45 | public static bool IsSslRedirected (HttpListenerRequest _req) {
|
---|
46 | string proto = _req.Headers ["X-Forwarded-Proto"];
|
---|
47 | return !string.IsNullOrEmpty (proto) && proto.Equals ("https", StringComparison.OrdinalIgnoreCase);
|
---|
48 | }
|
---|
49 |
|
---|
50 | public static string GenerateGuid () {
|
---|
51 | return Guid.NewGuid ().ToString ();
|
---|
52 | }
|
---|
53 | }
|
---|
54 | }
|
---|