using System.Net; using System.Text; using AllocsFixes.JSON; using HttpListenerResponse = SpaceWizards.HttpListener.HttpListenerResponse; namespace AllocsFixes.NetConnections.Servers.Web { public static class WebUtils { public const string MimePlain = "text/plain"; public const string MimeHtml = "text/html"; public const string MimeJson = "application/json"; #if ENABLE_PROFILER 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"); #endif public static void WriteJson (HttpListenerResponse _resp, JSONNode _root, HttpStatusCode _statusCode = HttpStatusCode.OK) { #if ENABLE_PROFILER jsonSerializeSampler.Begin (); #endif StringBuilder sb = new StringBuilder (); _root.ToString (sb); #if ENABLE_PROFILER jsonSerializeSampler.End (); netWriteSampler.Begin (); #endif WriteText (_resp, sb.ToString(), _statusCode, MimeJson); #if ENABLE_PROFILER netWriteSampler.End (); #endif } 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 string GenerateGuid () { return System.Guid.NewGuid ().ToString (); } } }