[387] | 1 | using System.Net;
|
---|
| 2 | using System.Text;
|
---|
| 3 | using AllocsFixes.JSON;
|
---|
| 4 | using HttpListenerResponse = SpaceWizards.HttpListener.HttpListenerResponse;
|
---|
| 5 |
|
---|
| 6 | namespace 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
|
---|
[389] | 27 | WriteText (_resp, sb.ToString(), _statusCode, MimeJson);
|
---|
[387] | 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) {
|
---|
[389] | 34 | _resp.StatusCode = (int)_statusCode;
|
---|
| 35 | _resp.ContentType = _mimeType ?? MimePlain;
|
---|
| 36 | _resp.ContentEncoding = Encoding.UTF8;
|
---|
| 37 |
|
---|
[387] | 38 | byte[] buf = Encoding.UTF8.GetBytes (_text);
|
---|
| 39 | _resp.ContentLength64 = buf.Length;
|
---|
| 40 | _resp.OutputStream.Write (buf, 0, buf.Length);
|
---|
| 41 | }
|
---|
| 42 |
|
---|
| 43 | public static string GenerateGuid () {
|
---|
| 44 | return System.Guid.NewGuid ().ToString ();
|
---|
| 45 | }
|
---|
| 46 | }
|
---|
| 47 | }
|
---|