Compare commits
5 Commits
ee20c9c5ec
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
| 8d55c1c533 | |||
| e4ee03364c | |||
| c77b3e0742 | |||
| e391f0238a | |||
| 823169ca91 |
Submodule DTLib.Demystifier updated: bb96774c37...4eaade6e92
@@ -2,7 +2,7 @@
|
||||
<PropertyGroup>
|
||||
<!--package info-->
|
||||
<PackageId>DTLib.Logging.Microsoft</PackageId>
|
||||
<Version>1.1.1</Version>
|
||||
<Version>1.1.3</Version>
|
||||
<Authors>Timerix</Authors>
|
||||
<Description>DTLib logger wrapper with dependency injection</Description>
|
||||
<RepositoryType>GIT</RepositoryType>
|
||||
@@ -11,7 +11,7 @@
|
||||
<Configuration>Release</Configuration>
|
||||
<PackageLicenseExpression>MIT</PackageLicenseExpression>
|
||||
<!--compilation properties-->
|
||||
<TargetFrameworks>netstandard2.0;netstandard2.1</TargetFrameworks>
|
||||
<TargetFramework>netstandard2.0</TargetFramework>
|
||||
<!--language features-->
|
||||
<LangVersion>latest</LangVersion>
|
||||
<Nullable>disable</Nullable>
|
||||
@@ -20,7 +20,7 @@
|
||||
|
||||
<!--external dependencies-->
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.Extensions.Logging" Version="8.0.0" />
|
||||
<PackageReference Include="Microsoft.Extensions.Logging" Version="9.0.5" />
|
||||
</ItemGroup>
|
||||
|
||||
<!--DTLib dependencies-->
|
||||
@@ -28,6 +28,6 @@
|
||||
<ProjectReference Include="..\DTLib\DTLib.csproj" />
|
||||
</ItemGroup>
|
||||
<ItemGroup Condition=" '$(Configuration)' != 'Debug' ">
|
||||
<PackageReference Include="DTLib" Version="1.6.*" />
|
||||
<PackageReference Include="DTLib" Version="1.7.4" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
<PropertyGroup>
|
||||
<!--package info-->
|
||||
<PackageId>DTLib.Web</PackageId>
|
||||
<Version>1.3.0</Version>
|
||||
<Version>1.4.0</Version>
|
||||
<Authors>Timerix</Authors>
|
||||
<Description>HTTP Server with simple routing</Description>
|
||||
<RepositoryType>GIT</RepositoryType>
|
||||
@@ -11,7 +11,7 @@
|
||||
<Configuration>Release</Configuration>
|
||||
<PackageLicenseExpression>MIT</PackageLicenseExpression>
|
||||
<!--compilation properties-->
|
||||
<TargetFrameworks>netstandard2.0;netstandard2.1</TargetFrameworks>
|
||||
<TargetFramework>netstandard2.0</TargetFramework>
|
||||
<AllowedOutputExtensionsInPackageBuildOutputFolder>$(AllowedOutputExtensionsInPackageBuildOutputFolder);.pdb</AllowedOutputExtensionsInPackageBuildOutputFolder>
|
||||
<!--language features-->
|
||||
<LangVersion>latest</LangVersion>
|
||||
@@ -25,6 +25,6 @@
|
||||
<ProjectReference Include="..\DTLib\DTLib.csproj" />
|
||||
</ItemGroup>
|
||||
<ItemGroup Condition=" '$(Configuration)' != 'Debug' ">
|
||||
<PackageReference Include="DTLib" Version="1.7.1" />
|
||||
<PackageReference Include="DTLib" Version="1.7.4" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
|
||||
@@ -1,15 +1,18 @@
|
||||
namespace DTLib.Web;
|
||||
|
||||
/// <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Methods"/>
|
||||
public enum HttpMethod
|
||||
[Flags]
|
||||
public enum HttpMethod : ushort
|
||||
{
|
||||
GET,
|
||||
POST,
|
||||
PUT,
|
||||
DELETE,
|
||||
PATCH,
|
||||
HEAD,
|
||||
OPTIONS,
|
||||
TRACE,
|
||||
CONNECT
|
||||
NONE = 0,
|
||||
GET = 1,
|
||||
POST = 2,
|
||||
PUT = 4,
|
||||
DELETE = 8,
|
||||
PATCH = 16,
|
||||
HEAD = 32,
|
||||
OPTIONS = 64,
|
||||
TRACE = 128,
|
||||
CONNECT = 256,
|
||||
ANY = 65535
|
||||
}
|
||||
@@ -2,5 +2,5 @@ namespace DTLib.Web.Routes;
|
||||
|
||||
public interface IRouter
|
||||
{
|
||||
Task<HttpStatusCode> Resolve(HttpListenerContext ctx, ContextLogger requestLogger);
|
||||
Task Resolve(HttpListenerContext ctx, ContextLogger requestLogger);
|
||||
}
|
||||
@@ -3,42 +3,63 @@ namespace DTLib.Web.Routes;
|
||||
public class SimpleRouter : IRouter
|
||||
{
|
||||
/// route for any url that doesn't have its own handler
|
||||
public IRouteHandler? DefaultRoute { get; set; }
|
||||
public record RouteWithMethod(HttpMethod method, IRouteHandler routeHandler)
|
||||
{
|
||||
public bool CheckMethod(HttpMethod requestMethod) => (requestMethod & method) != 0;
|
||||
|
||||
private readonly Dictionary<string, IRouteHandler> _routes = new();
|
||||
public bool CheckMethod(string requestMethodStr)
|
||||
=> Enum.TryParse<HttpMethod>(requestMethodStr, out var requestMethod)
|
||||
&& CheckMethod(requestMethod);
|
||||
}
|
||||
|
||||
private readonly Dictionary<string, RouteWithMethod> _routes = new();
|
||||
private readonly ILogger _logger;
|
||||
|
||||
public RouteWithMethod? DefaultRoute { get; set; }
|
||||
|
||||
public SimpleRouter(ILogger logger)
|
||||
{
|
||||
_logger = new ContextLogger(nameof(SimpleRouter), logger);
|
||||
}
|
||||
|
||||
public void MapRoute(string url, HttpMethod method, IRouteHandler route) => _routes.Add($"{url}:{method}", route);
|
||||
public void MapRoute(string url, HttpMethod method, IRouteHandler route)
|
||||
=> _routes.Add(url, new RouteWithMethod(method, route));
|
||||
|
||||
public void MapRoute(string url, HttpMethod method,
|
||||
Func<HttpListenerContext, ContextLogger, Task<HttpStatusCode>> route)
|
||||
=> MapRoute(url, method, new DelegateRouteHandler(route));
|
||||
|
||||
public async Task<HttpStatusCode> Resolve(HttpListenerContext ctx, ContextLogger requestLogger)
|
||||
public async Task Resolve(HttpListenerContext ctx, ContextLogger requestLogger)
|
||||
{
|
||||
HttpStatusCode status = HttpStatusCode.InternalServerError;
|
||||
try
|
||||
{
|
||||
|
||||
string? requestPath = ctx.Request.Url?.AbsolutePath;
|
||||
if (string.IsNullOrEmpty(requestPath))
|
||||
requestPath = "/";
|
||||
if (!_routes.TryGetValue($"{requestPath}:{ctx.Request.HttpMethod}", out var route))
|
||||
route = DefaultRoute;
|
||||
|
||||
HttpStatusCode status;
|
||||
if (route == null)
|
||||
if(!_routes.TryGetValue(requestPath!, out var routeWithMethod))
|
||||
routeWithMethod = DefaultRoute;
|
||||
|
||||
if (routeWithMethod is null)
|
||||
{
|
||||
_logger.LogWarn(nameof(SimpleRouter), $"couldn't resolve request path {requestPath}");
|
||||
_logger.LogWarn(nameof(SimpleRouter),
|
||||
$"couldn't resolve request path {ctx.Request.HttpMethod} {requestPath}");
|
||||
status = HttpStatusCode.NotFound;
|
||||
}
|
||||
else status = await route.HandleRequest(ctx, requestLogger);
|
||||
|
||||
else if (!routeWithMethod.CheckMethod(ctx.Request.HttpMethod))
|
||||
{
|
||||
_logger.LogWarn(nameof(SimpleRouter),
|
||||
$"received request with invalid method {ctx.Request.HttpMethod} {requestPath}");
|
||||
status = HttpStatusCode.MethodNotAllowed;
|
||||
}
|
||||
else status = await routeWithMethod.routeHandler.HandleRequest(ctx, requestLogger);
|
||||
}
|
||||
finally
|
||||
{
|
||||
ctx.Response.StatusCode = (int)status;
|
||||
await ctx.Response.OutputStream.FlushAsync();
|
||||
ctx.Response.OutputStream.Close();
|
||||
return status;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -58,9 +58,11 @@ public class WebApp
|
||||
requestLogger.LogInfo($"{ctx.Request.HttpMethod} {ctx.Request.RawUrl} from {ctx.Request.RemoteEndPoint}...");
|
||||
var stopwatch = new Stopwatch();
|
||||
stopwatch.Start();
|
||||
var status = await _router.Resolve(ctx, requestLogger);
|
||||
await _router.Resolve(ctx, requestLogger);
|
||||
stopwatch.Stop();
|
||||
requestLogger.LogInfo($"responded {(int)status} ({status}) in {stopwatch.ElapsedMilliseconds}ms");
|
||||
requestLogger.LogInfo($"responded {ctx.Response.StatusCode}" +
|
||||
$" ({(HttpStatusCode)ctx.Response.StatusCode})" +
|
||||
$" in {stopwatch.ElapsedMilliseconds}ms");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
|
||||
Submodule DTLib.XXHash updated: 9360dfe305...3e1a2c00e6
@@ -2,71 +2,79 @@ namespace DTLib.Console;
|
||||
|
||||
public class LaunchArgumentParser
|
||||
{
|
||||
public bool IsAllowedNoArguments;
|
||||
public string HelpMessageHeader = "USAGE:";
|
||||
public bool AllowedNoArguments;
|
||||
public bool AllowedUnknownArguments;
|
||||
// ReSharper disable once CollectionNeverQueried.Global
|
||||
public readonly List<string> UnknownArguments = new();
|
||||
|
||||
private readonly Dictionary<string, LaunchArgument> argDict = new();
|
||||
private readonly List<LaunchArgument> argList = new();
|
||||
|
||||
public class ExitAfterHelpException : Exception
|
||||
{
|
||||
internal ExitAfterHelpException() : base("your program can use this exception to exit after displaying help message")
|
||||
{ }
|
||||
}
|
||||
|
||||
public string CreateHelpMessage()
|
||||
{
|
||||
StringBuilder b = new();
|
||||
foreach (var arg in argList)
|
||||
arg.AppendHelpInfo(b).Append('\n');
|
||||
b.Remove(b.Length-1, 1);
|
||||
return b.ToString();
|
||||
}
|
||||
public string CreateHelpArgMessage(string argAlias)
|
||||
{
|
||||
StringBuilder b = new();
|
||||
var arg = Parse(argAlias);
|
||||
arg.AppendHelpInfo(b);
|
||||
return b.ToString();
|
||||
}
|
||||
private void HelpHandler()
|
||||
{
|
||||
System.Console.WriteLine(CreateHelpMessage());
|
||||
throw new ExitAfterHelpException();
|
||||
}
|
||||
|
||||
private void HelpArgHandler(string argAlias)
|
||||
{
|
||||
System.Console.WriteLine(CreateHelpArgMessage(argAlias));
|
||||
throw new ExitAfterHelpException();
|
||||
}
|
||||
|
||||
|
||||
public LaunchArgumentParser()
|
||||
{
|
||||
var help = new LaunchArgument(new[] { "h", "help" },
|
||||
"shows help message", HelpHandler);
|
||||
Add(help);
|
||||
var helpArg = new LaunchArgument(new[] { "ha", "helparg" },
|
||||
"shows help message for particular argument",
|
||||
HelpArgHandler, "argAlias");
|
||||
"shows help message for specific argument",
|
||||
HelpArgHandler, "argument");
|
||||
Add(helpArg);
|
||||
}
|
||||
public LaunchArgumentParser(ICollection<LaunchArgument> arguments) : this() => WithArgs(arguments);
|
||||
public LaunchArgumentParser(params LaunchArgument[] arguments) : this() => WithArgs(arguments);
|
||||
|
||||
public LaunchArgumentParser WithArgs(IEnumerable<LaunchArgument> args)
|
||||
{
|
||||
foreach (var arg in args)
|
||||
Add(arg);
|
||||
return this;
|
||||
}
|
||||
|
||||
public LaunchArgumentParser WithArgs(params LaunchArgument[] args)
|
||||
{
|
||||
foreach (var arg in args)
|
||||
Add(arg);
|
||||
return this;
|
||||
}
|
||||
|
||||
public LaunchArgumentParser WithHelpMessageHeader(string header)
|
||||
{
|
||||
HelpMessageHeader = header;
|
||||
return this;
|
||||
}
|
||||
|
||||
public LaunchArgumentParser AllowNoArguments()
|
||||
{
|
||||
IsAllowedNoArguments = true;
|
||||
AllowedNoArguments = true;
|
||||
return this;
|
||||
}
|
||||
|
||||
public LaunchArgumentParser(ICollection<LaunchArgument> arguments) : this()
|
||||
public LaunchArgumentParser AllowUnknownArguments()
|
||||
{
|
||||
foreach (var arg in arguments)
|
||||
Add(arg);
|
||||
AllowedUnknownArguments = true;
|
||||
return this;
|
||||
}
|
||||
public LaunchArgumentParser(params LaunchArgument[] arguments) : this()
|
||||
|
||||
|
||||
public string CreateHelpMessage()
|
||||
{
|
||||
foreach (var arg in arguments)
|
||||
Add(arg);
|
||||
StringBuilder b = new(HelpMessageHeader);
|
||||
foreach (var arg in argList)
|
||||
{
|
||||
b.Append('\n');
|
||||
arg.AppendHelpInfo(b);
|
||||
}
|
||||
return b.ToString();
|
||||
}
|
||||
|
||||
public string CreateHelpArgMessage(string argAlias)
|
||||
{
|
||||
StringBuilder b = new();
|
||||
if(!TryParseArg(argAlias, out var arg))
|
||||
throw new Exception($"unknown argument '{argAlias}'");
|
||||
arg.AppendHelpInfo(b);
|
||||
return b.ToString();
|
||||
}
|
||||
|
||||
public void Add(LaunchArgument arg)
|
||||
@@ -76,16 +84,13 @@ public class LaunchArgumentParser
|
||||
argDict.Add(alias, arg);
|
||||
}
|
||||
|
||||
public LaunchArgument Parse(string argAlias)
|
||||
public bool TryParseArg(string argAlias, out LaunchArgument arg)
|
||||
{
|
||||
// different argument providing patterns
|
||||
if (!argDict.TryGetValue(argAlias, out var arg) && // arg
|
||||
!(argAlias.StartsWith("--") && argDict.TryGetValue(argAlias.Substring(2), out arg)) && // --arg
|
||||
!(argAlias.StartsWith('-') && argDict.TryGetValue(argAlias.Substring(1), out arg)) && // -arg
|
||||
!(argAlias.StartsWith('/') && argDict.TryGetValue(argAlias.Substring(1), out arg))) // /arg
|
||||
throw new Exception($"invalid argument: {argAlias}\n{CreateHelpMessage()}");
|
||||
|
||||
return arg;
|
||||
arg = null!;
|
||||
return argAlias.StartsWith("--") && argDict.TryGetValue(argAlias.Substring(2), out arg) || // --arg
|
||||
argAlias.StartsWith('-') && argDict.TryGetValue(argAlias.Substring(1), out arg) || // -arg
|
||||
argAlias.StartsWith('/') && argDict.TryGetValue(argAlias.Substring(1), out arg); // /arg
|
||||
}
|
||||
|
||||
/// <param name="args">program launch args</param>
|
||||
@@ -95,18 +100,24 @@ public class LaunchArgumentParser
|
||||
public void ParseAndHandle(string[] args)
|
||||
{
|
||||
// show help message and throw ExitAfterHelpException
|
||||
if (args.Length == 0 && !IsAllowedNoArguments)
|
||||
if (args.Length == 0 && !AllowedNoArguments)
|
||||
HelpHandler();
|
||||
|
||||
List<LaunchArgument> execQueue = new();
|
||||
|
||||
for (int i = 0; i < args.Length; i++)
|
||||
{
|
||||
LaunchArgument arg = Parse(args[i]);
|
||||
if (!TryParseArg(args[i], out var arg))
|
||||
{
|
||||
if (!AllowedUnknownArguments)
|
||||
throw new Exception($"unknown argument '{args[i]}'");
|
||||
UnknownArguments.Add(args[i]);
|
||||
}
|
||||
for (int j = 0; j < arg.Params.Length; j++)
|
||||
{
|
||||
if (++i >= args.Length)
|
||||
throw new Exception($"argument '{arg.Aliases[0]}' should have parameter '{arg.Params[j]}' after it");
|
||||
throw new Exception(
|
||||
$"argument '{arg.Aliases[0]}' should have parameter '{arg.Params[j]}' after it");
|
||||
arg.Params[j].Value = args[i];
|
||||
}
|
||||
|
||||
@@ -119,4 +130,24 @@ public class LaunchArgumentParser
|
||||
foreach (var a in execQueue)
|
||||
a.Handle();
|
||||
}
|
||||
|
||||
private void HelpHandler()
|
||||
{
|
||||
System.Console.WriteLine(CreateHelpMessage());
|
||||
throw new ExitAfterHelpException();
|
||||
}
|
||||
|
||||
private void HelpArgHandler(string argAlias)
|
||||
{
|
||||
System.Console.WriteLine(CreateHelpArgMessage(argAlias));
|
||||
throw new ExitAfterHelpException();
|
||||
}
|
||||
|
||||
public class ExitAfterHelpException : Exception
|
||||
{
|
||||
public ExitAfterHelpException()
|
||||
: base("your program can use this exception to exit after displaying help message")
|
||||
{
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2,7 +2,7 @@
|
||||
<PropertyGroup>
|
||||
<!--package info-->
|
||||
<PackageId>DTLib</PackageId>
|
||||
<Version>1.7.1</Version>
|
||||
<Version>1.7.4</Version>
|
||||
<Authors>Timerix</Authors>
|
||||
<Description>Library for all my C# projects</Description>
|
||||
<RepositoryType>GIT</RepositoryType>
|
||||
@@ -31,6 +31,6 @@
|
||||
<ProjectReference Include="..\DTLib.Demystifier\DTLib.Demystifier.csproj" />
|
||||
</ItemGroup>
|
||||
<ItemGroup Condition=" '$(Configuration)' != 'Debug' ">
|
||||
<PackageReference Include="DTLib.Demystifier" Version="1.1.0" />
|
||||
<PackageReference Include="DTLib.Demystifier" Version="1.1.1" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
|
||||
Reference in New Issue
Block a user