Refactor route handling to use ConcurrentDictionary for thread-safe updates and optimize /goto/{path} logic

This commit is contained in:
2025-08-20 14:22:48 +03:30
parent 462f10ffb2
commit 866a5c57e3

View File

@@ -1,3 +1,4 @@
using System.Collections.Concurrent;
using Microsoft.AspNetCore.HttpOverrides;
using VirtualDDNSRouter.Server.Interfaces;
using VirtualDDNSRouter.Server.Services;
@@ -21,7 +22,7 @@ app.UseForwardedHeaders(new ForwardedHeadersOptions
if (app.Environment.IsDevelopment()) app.MapOpenApi();
var routes = new List<Route>();
var routes = new ConcurrentDictionary<string, Route>();
app.MapGet("/setip/{path}/{port}/{apiKey}",
async (IYamlParser yamlParser, HttpContext context, string path, ushort port, string apiKey) =>
@@ -42,24 +43,20 @@ app.MapGet("/setip/{path}/{port}/{apiKey}",
return Results.BadRequest("Could not get the client ip address");
}
var existingRoute = routes.FirstOrDefault(r => r.path == path);
if (existingRoute is not null) routes.Remove(existingRoute);
routes.Add(new Route
routes[path] = new Route
{
ipAddress = clientIp,
path = path,
port = port
});
};
return Results.Ok($"goto/{path}");
});
app.MapGet("/goto/{path}", (string path) =>
{
var redirectRoute = routes.FirstOrDefault(r => r.path == path);
if (redirectRoute is null) return Task.FromResult(Results.NotFound());
return Task.FromResult(Results.Redirect($"http://{redirectRoute.ipAddress}:{redirectRoute.port}"));
if (routes.TryGetValue(path, out var route)) return Results.Redirect($"http://{route.ipAddress}:{route.port}");
return Results.NotFound();
});
app.Run();