source: TFP-WebServer/WebServer/src/WebUtils.cs@ 449

Last change on this file since 449 was 434, checked in by alloc, 19 months ago

Added permission management APIs

File size: 6.0 KB
Line 
1using System;
2using System.Collections.Specialized;
3using System.Diagnostics.CodeAnalysis;
4using System.Net;
5using System.Text;
6using UnityEngine.Profiling;
7using Utf8Json;
8using Webserver.WebAPI;
9using HttpListenerRequest = SpaceWizards.HttpListener.HttpListenerRequest;
10using HttpListenerResponse = SpaceWizards.HttpListener.HttpListenerResponse;
11
12namespace Webserver {
13 public static class WebUtils {
14 static WebUtils () {
15 JsonWriter writer = new JsonWriter ();
16 writer.WriteBeginArray ();
17 writer.WriteEndArray ();
18 JsonEmptyData = writer.ToUtf8ByteArray ();
19 }
20
21 // ReSharper disable once MemberCanBePrivate.Global
22 public const string MimePlain = "text/plain";
23 public const string MimeHtml = "text/html";
24 // ReSharper disable once MemberCanBePrivate.Global
25 public const string MimeJson = "application/json";
26
27 private static readonly CustomSampler envelopeBuildSampler = CustomSampler.Create ("JSON_EnvelopeBuilding");
28 private static readonly CustomSampler netWriteSampler = CustomSampler.Create ("JSON_Write");
29
30 public static void WriteText (HttpListenerResponse _resp, string _text, HttpStatusCode _statusCode = HttpStatusCode.OK, string _mimeType = null) {
31 _resp.StatusCode = (int)_statusCode;
32 _resp.ContentType = _mimeType ?? MimePlain;
33 _resp.ContentEncoding = Encoding.UTF8;
34
35 if (string.IsNullOrEmpty (_text)) {
36 _resp.ContentLength64 = 0;
37 } else {
38 byte[] buf = Encoding.UTF8.GetBytes (_text);
39 _resp.ContentLength64 = buf.Length;
40 _resp.OutputStream.Write (buf, 0, buf.Length);
41 }
42 }
43
44 public static bool IsSslRedirected (HttpListenerRequest _req) {
45 string proto = _req.Headers ["X-Forwarded-Proto"];
46 return !string.IsNullOrEmpty (proto) && proto.Equals ("https", StringComparison.OrdinalIgnoreCase);
47 }
48
49 public static string GenerateGuid () {
50 return Guid.NewGuid ().ToString ();
51 }
52
53 [SuppressMessage ("ReSharper", "MemberCanBePrivate.Global")]
54 public static void WriteJsonData (HttpListenerResponse _resp, ref JsonWriter _jsonWriter, HttpStatusCode _statusCode = HttpStatusCode.OK) {
55 ArraySegment<byte> jsonData = _jsonWriter.GetBuffer ();
56
57 netWriteSampler.Begin ();
58 _resp.StatusCode = (int)_statusCode;
59 _resp.ContentType = MimeJson;
60 _resp.ContentEncoding = Encoding.UTF8;
61 _resp.ContentLength64 = jsonData.Count;
62 _resp.OutputStream.Write (jsonData.Array!, 0, jsonData.Count);
63 netWriteSampler.End ();
64 }
65
66 public static readonly byte[] JsonEmptyData;
67
68 private static readonly byte[] jsonRawDataKey = JsonWriter.GetEncodedPropertyNameWithBeginObject ("data"); // {"data":
69
70 private static readonly byte[] jsonRawMetaKey = JsonWriter.GetEncodedPropertyNameWithPrefixValueSeparator ("meta"); // ,"meta":
71 private static readonly byte[] jsonRawMetaServertimeKey = JsonWriter.GetEncodedPropertyNameWithBeginObject ("serverTime"); // {"serverTime":
72 private static readonly byte[] jsonRawMetaRequestMethodKey = JsonWriter.GetEncodedPropertyNameWithPrefixValueSeparator ("requestMethod"); // ,"requestMethod":
73 private static readonly byte[] jsonRawMetaRequestSubpathKey = JsonWriter.GetEncodedPropertyNameWithPrefixValueSeparator ("requestSubpath"); // ,"requestSubpath":
74 private static readonly byte[] jsonRawMetaRequestBodyKey = JsonWriter.GetEncodedPropertyNameWithPrefixValueSeparator ("requestBody"); // ,"requestBody":
75 private static readonly byte[] jsonRawMetaErrorCodeKey = JsonWriter.GetEncodedPropertyNameWithPrefixValueSeparator ("errorCode"); // ,"errorCode":
76 private static readonly byte[] jsonRawMetaExceptionMessageKey = JsonWriter.GetEncodedPropertyNameWithPrefixValueSeparator ("exceptionMessage"); // ,"exceptionMessage":
77 private static readonly byte[] jsonRawMetaExceptionTraceKey = JsonWriter.GetEncodedPropertyNameWithPrefixValueSeparator ("exceptionTrace"); // ,"exceptionTrace":
78
79 public static void PrepareEnvelopedResult (out JsonWriter _writer) {
80 _writer = new JsonWriter ();
81 _writer.WriteRaw (jsonRawDataKey);
82 }
83
84 public static void SendEnvelopedResult (RequestContext _context, ref JsonWriter _writer, HttpStatusCode _statusCode = HttpStatusCode.OK,
85 byte[] _jsonInputData = null, string _errorCode = null, Exception _exception = null) {
86
87 envelopeBuildSampler.Begin ();
88
89 _writer.WriteRaw (jsonRawMetaKey);
90
91 _writer.WriteRaw (jsonRawMetaServertimeKey);
92 JsonCommons.WriteDateTime (ref _writer, DateTime.Now);
93
94 if (!string.IsNullOrEmpty (_errorCode)) {
95 _writer.WriteRaw (jsonRawMetaRequestMethodKey);
96 _writer.WriteString (_context.Request.HttpMethod);
97
98 _writer.WriteRaw (jsonRawMetaRequestSubpathKey);
99 _writer.WriteString (_context.RequestPath);
100
101 _writer.WriteRaw (jsonRawMetaRequestBodyKey);
102 if (_jsonInputData != null) {
103 _writer.WriteRaw (_jsonInputData);
104 } else {
105 _writer.WriteNull ();
106 }
107
108 _writer.WriteRaw (jsonRawMetaErrorCodeKey);
109 _writer.WriteString (_errorCode);
110
111 if (_exception != null) {
112 _writer.WriteRaw (jsonRawMetaExceptionMessageKey);
113 _writer.WriteString (_exception.Message);
114
115 _writer.WriteRaw (jsonRawMetaExceptionTraceKey);
116 _writer.WriteString (_exception.StackTrace);
117 }
118 }
119
120 _writer.WriteEndObject (); // End of "meta" object
121 _writer.WriteEndObject (); // End of overall result object
122
123 envelopeBuildSampler.End ();
124
125 WriteJsonData (_context.Response, ref _writer, _statusCode);
126 }
127
128 public static void SendEmptyResponse (RequestContext _context, HttpStatusCode _statusCode = HttpStatusCode.OK, byte[] _jsonInputData = null, string _errorCode = null, Exception _exception = null) {
129 PrepareEnvelopedResult (out JsonWriter writer);
130 writer.WriteRaw (JsonEmptyData);
131 SendEnvelopedResult (_context, ref writer, _statusCode, _jsonInputData, _errorCode, _exception);
132 }
133
134
135 public static bool TryGetValue (this NameValueCollection _nameValueCollection, string _name, out string _result) {
136 _result = _nameValueCollection [_name];
137 return _result != null;
138 }
139 }
140}
Note: See TracBrowser for help on using the repository browser.