~furry/mamoru-server

fece8af3dc33179c67cdd61a99e437a664394f77 — nora 2 months ago cf98d8e
fix route matching
2 files changed, 19 insertions(+), 19 deletions(-)

M Managers/RoutesManager.cs
M Models.Mamoru/Status.cs
M Managers/RoutesManager.cs => Managers/RoutesManager.cs +18 -18
@@ 1,36 1,35 @@
using System.Net;
using System.Reflection;
using Exiled.API.Extensions;
using Exiled.API.Features;
using Mamoru.Connections;
using Mamoru.Utils;
using WebSocketSharp.Server;
using HttpStatusCode = WebSocketSharp.Net.HttpStatusCode;

namespace Mamoru.Managers;

public class RoutesManager {
  private readonly HttpServer _httpServer = new(IPAddress.Loopback, 4649);
  private readonly Dictionary<string, AbstractRoute> _httpRoutes = new();
  public readonly Dictionary<string, AbstractRoute> HttpRoutes = new();

  public RoutesManager() {
    StartHttpServer();
  }

  private void HandleRequest(object sender, HttpRequestEventArgs ev) {
    // _httpServer.OnGet += (_, e) => {
    //   var req = e.Request;
    //   var res = e.Response;
    //
    //   var route = httpRoutes[req.RawUrl];
    //   if (route == null) {
    //     EmptyResponse.Create(ref res, HttpStatusCode.NotFound);
    //     return;
    //   }
    //
    //   route.Get(ref req, ref res);
    // };
    Log.Info($"{ev.Request.HttpMethod} {ev.Request.RawUrl}");
    Log.Info(string.Join(Environment.NewLine, _httpRoutes));
    var req = ev.Request;
    var res = ev.Response;
    var path = req.RawUrl;
    var route = HttpRoutes.TryGetValue(path, out var r) ? r : null;
    Log.Info($"{req.HttpMethod} {path}");
    if (route is null) {
      EmptyResponse.Create(ref res, HttpStatusCode.NotFound);
      return;
    }

    var methodName = req.HttpMethod[0] + req.HttpMethod.ToLower().Substring(1);
    var method = route.GetType().GetMethod(methodName);
    method!.Invoke(route, [req, res]);
  }

  private void LoadRoutes() {


@@ 42,7 41,7 @@ public class RoutesManager {
      .ForEach((type) => {
        try {
          var clazz = (AbstractRoute)Activator.CreateInstance(type);
          _httpRoutes[clazz.Path] = clazz;
          HttpRoutes[clazz.Path] = clazz;
          Log.Info($"Loaded http route {type.Name} at {clazz.Path}");
        }
        catch {


@@ 70,9 69,10 @@ public class RoutesManager {

    Log.Info("Registering HandleRequest events...");
    RegisterEvents();
    

    Log.Info("Starting HTTP server...");
    _httpServer.Start();
    Log.Info($"HTTP server listening on port {_httpServer.Port}");
  }

  public void StopHttpServer() {

M Models.Mamoru/Status.cs => Models.Mamoru/Status.cs +1 -1
@@ 5,4 5,4 @@ public record Status(
  bool Webhooks,
  string ExiledVersion,
  string MamoruVersion
);
\ No newline at end of file
);