Refactor route handling to use ConcurrentDictionary
for thread-safe updates and optimize /goto/{path}
logic
This commit is contained in:
@@ -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();
|
Reference in New Issue
Block a user