using System; using System.Net; using System.Text; using AllocsFixes.JSON; using HttpListenerRequest = SpaceWizards.HttpListener.HttpListenerRequest; using HttpListenerResponse = SpaceWizards.HttpListener.HttpListenerResponse; namespace Webserver { public static class WebUtils { public const string MimePlain = "text/plain"; public const string MimeHtml = "text/html"; public const string MimeJson = "application/json"; private static readonly UnityEngine.Profiling.CustomSampler jsonSerializeSampler = UnityEngine.Profiling.CustomSampler.Create ("JSON_Serialize"); private static readonly UnityEngine.Profiling.CustomSampler netWriteSampler = UnityEngine.Profiling.CustomSampler.Create ("JSON_Write"); public static void WriteJson (HttpListenerResponse _resp, JsonNode _root, HttpStatusCode _statusCode = HttpStatusCode.OK) { jsonSerializeSampler.Begin (); StringBuilder sb = new StringBuilder (); _root.ToString (sb); jsonSerializeSampler.End (); netWriteSampler.Begin (); WriteText (_resp, sb.ToString(), _statusCode, MimeJson); netWriteSampler.End (); } public static void WriteText (HttpListenerResponse _resp, string _text, HttpStatusCode _statusCode = HttpStatusCode.OK, string _mimeType = null) { _resp.StatusCode = (int)_statusCode; _resp.ContentType = _mimeType ?? MimePlain; _resp.ContentEncoding = Encoding.UTF8; byte[] buf = Encoding.UTF8.GetBytes (_text); _resp.ContentLength64 = buf.Length; _resp.OutputStream.Write (buf, 0, buf.Length); } public static bool IsSslRedirected (HttpListenerRequest _req) { string proto = _req.Headers ["X-Forwarded-Proto"]; return !string.IsNullOrEmpty (proto) && proto.Equals ("https", StringComparison.OrdinalIgnoreCase); } public static string GenerateGuid () { return Guid.NewGuid ().ToString (); } } }