source: binary-improvements2/WebServer/src/WebUtils.cs@ 402

Last change on this file since 402 was 402, checked in by alloc, 22 months ago
  • Major refactoring
  • Using Utf8Json for (de)serialization
  • Moving APIs to REST
  • Removing dependencies from WebServer and MapRenderer to ServerFixes
File size: 5.1 KB
Line 
1using System;
2using System.Diagnostics.CodeAnalysis;
3using System.Net;
4using System.Text;
5using Utf8Json;
6using HttpListenerRequest = SpaceWizards.HttpListener.HttpListenerRequest;
7using HttpListenerResponse = SpaceWizards.HttpListener.HttpListenerResponse;
8
9namespace Webserver {
10 public static class WebUtils {
11 // ReSharper disable once MemberCanBePrivate.Global
12 public const string MimePlain = "text/plain";
13 public const string MimeHtml = "text/html";
14 // ReSharper disable once MemberCanBePrivate.Global
15 public const string MimeJson = "application/json";
16
17 private static readonly UnityEngine.Profiling.CustomSampler envelopeBuildSampler = UnityEngine.Profiling.CustomSampler.Create ("JSON_EnvelopeBuilding");
18 private static readonly UnityEngine.Profiling.CustomSampler netWriteSampler = UnityEngine.Profiling.CustomSampler.Create ("JSON_Write");
19
20 public static void WriteText (HttpListenerResponse _resp, string _text, HttpStatusCode _statusCode = HttpStatusCode.OK, string _mimeType = null) {
21 _resp.StatusCode = (int)_statusCode;
22 _resp.ContentType = _mimeType ?? MimePlain;
23 _resp.ContentEncoding = Encoding.UTF8;
24
25 byte[] buf = Encoding.UTF8.GetBytes (_text);
26 _resp.ContentLength64 = buf.Length;
27 _resp.OutputStream.Write (buf, 0, buf.Length);
28 }
29
30 public static bool IsSslRedirected (HttpListenerRequest _req) {
31 string proto = _req.Headers ["X-Forwarded-Proto"];
32 return !string.IsNullOrEmpty (proto) && proto.Equals ("https", StringComparison.OrdinalIgnoreCase);
33 }
34
35 public static string GenerateGuid () {
36 return Guid.NewGuid ().ToString ();
37 }
38
39 [SuppressMessage ("ReSharper", "MemberCanBePrivate.Global")]
40 public static void WriteJsonData (HttpListenerResponse _resp, ref JsonWriter _jsonWriter, HttpStatusCode _statusCode = HttpStatusCode.OK) {
41 ArraySegment<byte> jsonData = _jsonWriter.GetBuffer ();
42
43 netWriteSampler.Begin ();
44 _resp.StatusCode = (int)_statusCode;
45 _resp.ContentType = MimeJson;
46 _resp.ContentEncoding = Encoding.UTF8;
47 _resp.ContentLength64 = jsonData.Count;
48 _resp.OutputStream.Write (jsonData.Array!, 0, jsonData.Count);
49 netWriteSampler.End ();
50 }
51
52
53 private static readonly byte[] jsonRawDataKey = JsonWriter.GetEncodedPropertyNameWithBeginObject ("data"); // {"data":
54
55 private static readonly byte[] jsonRawMetaKey = JsonWriter.GetEncodedPropertyNameWithPrefixValueSeparator ("meta"); // ,"meta":
56 private static readonly byte[] jsonRawMetaServertimeKey = JsonWriter.GetEncodedPropertyNameWithBeginObject ("serverTime"); // {"serverTime":
57 private static readonly byte[] jsonRawMetaRequestMethodKey = JsonWriter.GetEncodedPropertyNameWithPrefixValueSeparator ("requestMethod"); // ,"requestMethod":
58 private static readonly byte[] jsonRawMetaRequestSubpathKey = JsonWriter.GetEncodedPropertyNameWithPrefixValueSeparator ("requestSubpath"); // ,"requestSubpath":
59 private static readonly byte[] jsonRawMetaRequestBodyKey = JsonWriter.GetEncodedPropertyNameWithPrefixValueSeparator ("requestBody"); // ,"requestBody":
60 private static readonly byte[] jsonRawMetaErrorCodeKey = JsonWriter.GetEncodedPropertyNameWithPrefixValueSeparator ("errorCode"); // ,"errorCode":
61 private static readonly byte[] jsonRawMetaExceptionMessageKey = JsonWriter.GetEncodedPropertyNameWithPrefixValueSeparator ("exceptionMessage"); // ,"exceptionMessage":
62 private static readonly byte[] jsonRawMetaExceptionTraceKey = JsonWriter.GetEncodedPropertyNameWithPrefixValueSeparator ("exceptionTrace"); // ,"exceptionTrace":
63
64 public static void PrepareEnvelopedResult (out JsonWriter _writer) {
65 _writer = new JsonWriter ();
66 _writer.WriteRaw (jsonRawDataKey);
67 }
68
69 public static void SendEnvelopedResult (RequestContext _context, ref JsonWriter _writer, HttpStatusCode _statusCode = HttpStatusCode.OK,
70 byte[] _jsonInputData = null, string _errorCode = null, Exception _exception = null) {
71
72 envelopeBuildSampler.Begin ();
73
74 _writer.WriteRaw (jsonRawMetaKey);
75
76 _writer.WriteRaw (jsonRawMetaServertimeKey);
77 _writer.WriteString (DateTime.Now.ToString ("o"));
78
79 if (!string.IsNullOrEmpty (_errorCode)) {
80 _writer.WriteRaw (jsonRawMetaRequestMethodKey);
81 _writer.WriteString (_context.Request.HttpMethod);
82
83 _writer.WriteRaw (jsonRawMetaRequestSubpathKey);
84 _writer.WriteString (_context.RequestPath);
85
86 _writer.WriteRaw (jsonRawMetaRequestBodyKey);
87 if (_jsonInputData != null) {
88 _writer.WriteRaw (_jsonInputData);
89 } else {
90 _writer.WriteNull ();
91 }
92
93 _writer.WriteRaw (jsonRawMetaErrorCodeKey);
94 _writer.WriteString (_errorCode);
95
96 if (_exception != null) {
97 _writer.WriteRaw (jsonRawMetaExceptionMessageKey);
98 _writer.WriteString (_exception.Message);
99
100 _writer.WriteRaw (jsonRawMetaExceptionTraceKey);
101 _writer.WriteString (_exception.StackTrace);
102 }
103 }
104
105 _writer.WriteEndObject (); // End of "meta" object
106 _writer.WriteEndObject (); // End of overall result object
107
108 envelopeBuildSampler.End ();
109
110 WriteJsonData (_context.Response, ref _writer, _statusCode);
111 }
112 }
113}
Note: See TracBrowser for help on using the repository browser.