This commit is contained in:
2024-04-19 21:23:15 +02:00
parent 0ab2ae03ce
commit 7e5fa6ce41
4 changed files with 1023 additions and 1 deletions

View File

@ -10,7 +10,7 @@ using Tranga.NotificationConnectors;
namespace Tranga;
public class Server : GlobalBase
public partial class Server : GlobalBase
{
private readonly HttpListener _listener = new ();
private readonly Tranga _parent;
@ -68,6 +68,12 @@ public class Server : GlobalBase
if(request.Url!.LocalPath.Contains("favicon"))
SendResponse(HttpStatusCode.NoContent, response);
if (Regex.IsMatch(request.Url.LocalPath, ""))
{
HandleRequestV2(context);
return;
}
switch (request.HttpMethod)
{
case "GET":

80
Tranga/ServerV2.cs Normal file
View File

@ -0,0 +1,80 @@
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using Newtonsoft.Json;
namespace Tranga;
public partial class Server
{
private void HandleRequestV2(HttpListenerContext context)
{
HttpListenerRequest request = context.Request;
HttpListenerResponse response = context.Response;
string path = Regex.Match(request.Url!.LocalPath, @"[A-z0-9]+(\/[A-z0-9]+)*").Value;
Dictionary<string, string> requestVariables = GetRequestVariables(request.Url!.Query); //Variables in the URI
Dictionary<string, string> requestBody = GetRequestBody(request); //Variables in the JSON body
Dictionary<string, string> requestParams = requestVariables.UnionBy(requestBody, v => v.Key)
.ToDictionary(kv => kv.Key, kv => kv.Value); //The actual variable used for the API
switch (request.HttpMethod)
{
case "GET":
HandleGetV2(path, response, requestParams);
break;
case "POST":
HandlePostV2(path, response, requestParams);
break;
case "DELETE":
HandleDeleteV2(path, response, requestParams);
break;
default:
SendResponse(HttpStatusCode.MethodNotAllowed, response);
break;
}
}
private Dictionary<string, string> GetRequestBody(HttpListenerRequest request)
{
if (!request.HasEntityBody)
{
Log("No request body");
return new Dictionary<string, string>();
}
Stream body = request.InputStream;
Encoding encoding = request.ContentEncoding;
using StreamReader streamReader = new (body, encoding);
try
{
Dictionary<string, string> requestBody =
JsonConvert.DeserializeObject<Dictionary<string, string>>(streamReader.ReadToEnd())
?? new();
return requestBody;
}
catch (JsonException e)
{
Log(e.Message);
}
return new Dictionary<string, string>();
}
private void HandleGetV2(string path, HttpListenerResponse response,
Dictionary<string, string> requestParameters)
{
throw new NotImplementedException("v2 not implemented yet");
}
private void HandlePostV2(string path, HttpListenerResponse response,
Dictionary<string, string> requestParameters)
{
throw new NotImplementedException("v2 not implemented yet");
}
private void HandleDeleteV2(string path, HttpListenerResponse response,
Dictionary<string, string> requestParameters)
{
throw new NotImplementedException("v2 not implemented yet");
}
}