Refactor route handling to use ConcurrentDictionary for thread-safe updates and optimize /goto/{path} logic
This commit is contained in:
1 parent
462f10ffb2
commit
866a5c57e3
1 file changed
+6
-9
@@ -1,3 +1,4 @@
|
|||||||
|
using System.Collections.Concurrent;
|
||||||
using Microsoft.AspNetCore.HttpOverrides;
|
using Microsoft.AspNetCore.HttpOverrides;
|
||||||
using VirtualDDNSRouter.Server.Interfaces;
|
using VirtualDDNSRouter.Server.Interfaces;
|
||||||
using VirtualDDNSRouter.Server.Services;
|
using VirtualDDNSRouter.Server.Services;
|
||||||
@@ -21,7 +22,7 @@ app.UseForwardedHeaders(new ForwardedHeadersOptions
|
|||||||
|
|
||||||
if (app.Environment.IsDevelopment()) app.MapOpenApi();
|
if (app.Environment.IsDevelopment()) app.MapOpenApi();
|
||||||
|
|
||||||
var routes = new List<Route>();
|
var routes = new ConcurrentDictionary<string, Route>();
|
||||||
|
|
||||||
app.MapGet("/setip/{path}/{port}/{apiKey}",
|
app.MapGet("/setip/{path}/{port}/{apiKey}",
|
||||||
async (IYamlParser yamlParser, HttpContext context, string path, ushort port, string 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");
|
return Results.BadRequest("Could not get the client ip address");
|
||||||
}
|
}
|
||||||
|
|
||||||
var existingRoute = routes.FirstOrDefault(r => r.path == path);
|
routes[path] = new Route
|
||||||
if (existingRoute is not null) routes.Remove(existingRoute);
|
|
||||||
|
|
||||||
routes.Add(new Route
|
|
||||||
{
|
{
|
||||||
ipAddress = clientIp,
|
ipAddress = clientIp,
|
||||||
path = path,
|
path = path,
|
||||||
port = port
|
port = port
|
||||||
});
|
};
|
||||||
|
|
||||||
return Results.Ok($"goto/{path}");
|
return Results.Ok($"goto/{path}");
|
||||||
});
|
});
|
||||||
|
|
||||||
app.MapGet("/goto/{path}", (string path) =>
|
app.MapGet("/goto/{path}", (string path) =>
|
||||||
{
|
{
|
||||||
var redirectRoute = routes.FirstOrDefault(r => r.path == path);
|
if (routes.TryGetValue(path, out var route)) return Results.Redirect($"http://{route.ipAddress}:{route.port}");
|
||||||
if (redirectRoute is null) return Task.FromResult(Results.NotFound());
|
return Results.NotFound();
|
||||||
return Task.FromResult(Results.Redirect($"http://{redirectRoute.ipAddress}:{redirectRoute.port}"));
|
|
||||||
});
|
});
|
||||||
|
|
||||||
app.Run();
|
app.Run();
|
||||||
Reference in new issue
Block a user