1 | using System.Net; |
---|
2 | using System.Text; |
---|
3 | using AllocsFixes.JSON; |
---|
4 | using UnityEngine.Profiling; |
---|
5 | |
---|
6 | namespace AllocsFixes.NetConnections.Servers.Web.API { |
---|
7 | public abstract class WebAPI { |
---|
8 | public readonly string Name; |
---|
9 | |
---|
10 | protected WebAPI () { |
---|
11 | Name = GetType ().Name; |
---|
12 | } |
---|
13 | |
---|
14 | #if ENABLE_PROFILER |
---|
15 | private static readonly CustomSampler jsonSerializeSampler = CustomSampler.Create ("JSON_Serialize"); |
---|
16 | private static readonly CustomSampler netWriteSampler = CustomSampler.Create ("JSON_Write"); |
---|
17 | #endif |
---|
18 | |
---|
19 | public static void WriteJSON (HttpListenerResponse resp, JSONNode root) { |
---|
20 | #if ENABLE_PROFILER |
---|
21 | jsonSerializeSampler.Begin (); |
---|
22 | #endif |
---|
23 | StringBuilder sb = new StringBuilder (); |
---|
24 | root.ToString (sb); |
---|
25 | #if ENABLE_PROFILER |
---|
26 | jsonSerializeSampler.End (); |
---|
27 | netWriteSampler.Begin (); |
---|
28 | #endif |
---|
29 | byte[] buf = Encoding.UTF8.GetBytes (sb.ToString ()); |
---|
30 | resp.ContentLength64 = buf.Length; |
---|
31 | resp.ContentType = "application/json"; |
---|
32 | resp.ContentEncoding = Encoding.UTF8; |
---|
33 | resp.OutputStream.Write (buf, 0, buf.Length); |
---|
34 | #if ENABLE_PROFILER |
---|
35 | netWriteSampler.End (); |
---|
36 | #endif |
---|
37 | } |
---|
38 | |
---|
39 | public static void WriteText (HttpListenerResponse _resp, string _text) { |
---|
40 | byte[] buf = Encoding.UTF8.GetBytes (_text); |
---|
41 | _resp.ContentLength64 = buf.Length; |
---|
42 | _resp.ContentType = "text/plain"; |
---|
43 | _resp.ContentEncoding = Encoding.UTF8; |
---|
44 | _resp.OutputStream.Write (buf, 0, buf.Length); |
---|
45 | } |
---|
46 | |
---|
47 | public abstract void HandleRequest (HttpListenerRequest req, HttpListenerResponse resp, WebConnection user, |
---|
48 | int permissionLevel); |
---|
49 | |
---|
50 | public virtual int DefaultPermissionLevel () { |
---|
51 | return 0; |
---|
52 | } |
---|
53 | } |
---|
54 | } |
---|