[391] | 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 | 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 | }
|
---|