Compare commits
11
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
be9dd343bc | ||
|
|
fb91d099ac | ||
|
|
4571b979fd | ||
|
|
d2a3a82b95 | ||
|
|
6ad805841d | ||
|
|
d152b8f3ae | ||
|
|
81dd1f8bd5 | ||
|
|
c4db0f2d2c | ||
|
|
f01672f714 | ||
|
|
03ebfa1321 | ||
|
|
8d0419b6ac |
@@ -0,0 +1,21 @@
|
|||||||
|
MIT License
|
||||||
|
|
||||||
|
Copyright (c) 2024 00asdf, GHXX
|
||||||
|
|
||||||
|
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
|
of this software and associated documentation files (the "Software"), to deal
|
||||||
|
in the Software without restriction, including without limitation the rights
|
||||||
|
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||||
|
copies of the Software, and to permit persons to whom the Software is
|
||||||
|
furnished to do so, subject to the following conditions:
|
||||||
|
|
||||||
|
The above copyright notice and this permission notice shall be included in all
|
||||||
|
copies or substantial portions of the Software.
|
||||||
|
|
||||||
|
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
|
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
|
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||||
|
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||||
|
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||||
|
SOFTWARE.
|
||||||
@@ -24,7 +24,7 @@ public sealed class HttpServer {
|
|||||||
Port = port;
|
Port = port;
|
||||||
conf = configuration;
|
conf = configuration;
|
||||||
listener = new HttpListener();
|
listener = new HttpListener();
|
||||||
listener.Prefixes.Add($"http://localhost:{port}/");
|
listener.Prefixes.Add($"http://127.0.0.1:{port}/");
|
||||||
mainLogger = new(LogOutputTopic.Main, conf);
|
mainLogger = new(LogOutputTopic.Main, conf);
|
||||||
requestLogger = new(LogOutputTopic.Request, conf);
|
requestLogger = new(LogOutputTopic.Request, conf);
|
||||||
}
|
}
|
||||||
@@ -89,6 +89,7 @@ public sealed class HttpServer {
|
|||||||
private readonly Dictionary<string, PathTree<EndpointInvocationInfo>> pathEndpointMethodInfosTrees = new(); // reqmethod : pathtree
|
private readonly Dictionary<string, PathTree<EndpointInvocationInfo>> pathEndpointMethodInfosTrees = new(); // reqmethod : pathtree
|
||||||
private static readonly Type[] expectedEndpointParameterTypes = new[] { typeof(RequestContext) };
|
private static readonly Type[] expectedEndpointParameterTypes = new[] { typeof(RequestContext) };
|
||||||
internal static readonly int expectedEndpointParameterPrefixCount = expectedEndpointParameterTypes.Length;
|
internal static readonly int expectedEndpointParameterPrefixCount = expectedEndpointParameterTypes.Length;
|
||||||
|
private readonly Dictionary<string, Func<RequestContext, Task<bool>>> wildcardFallbackHandlers = new(); // reqmethod : handler
|
||||||
|
|
||||||
public void RegisterEndpointsFromType<T>(Func<T>? instanceFactory = null) where T : class { // T cannot be static, as generic args must be nonstatic
|
public void RegisterEndpointsFromType<T>(Func<T>? instanceFactory = null) where T : class { // T cannot be static, as generic args must be nonstatic
|
||||||
if (stringToTypeParameterConverters.Count == 0)
|
if (stringToTypeParameterConverters.Count == 0)
|
||||||
@@ -213,7 +214,7 @@ public sealed class HttpServer {
|
|||||||
|
|
||||||
private readonly Dictionary<Type, IParameterConverter> stringToTypeParameterConverters = new();
|
private readonly Dictionary<Type, IParameterConverter> stringToTypeParameterConverters = new();
|
||||||
|
|
||||||
private static string NormalizeUrlPath(string url) {
|
private string NormalizeUrlPath(string url) {
|
||||||
var fwdSlashUrl = url.Replace('\\', '/');
|
var fwdSlashUrl = url.Replace('\\', '/');
|
||||||
|
|
||||||
var segments = fwdSlashUrl.Trim('/').Split('/', StringSplitOptions.RemoveEmptyEntries).ToList();
|
var segments = fwdSlashUrl.Trim('/').Split('/', StringSplitOptions.RemoveEmptyEntries).ToList();
|
||||||
@@ -242,7 +243,12 @@ public sealed class HttpServer {
|
|||||||
}
|
}
|
||||||
rv.AppendJoin('/', simplifiedSegmentsReversed.Reverse<string>());
|
rv.AppendJoin('/', simplifiedSegmentsReversed.Reverse<string>());
|
||||||
|
|
||||||
return '/' + (rv.ToString().TrimEnd('/') + (fwdSlashUrl.EndsWith('/') ? "/" : "")).TrimStart('/');
|
var suffix = (rv.ToString().TrimEnd('/') + (fwdSlashUrl.EndsWith('/') ? "/" : "")).TrimStart('/');
|
||||||
|
if (conf.TrimTrailingSlash) {
|
||||||
|
suffix = suffix.TrimEnd('/');
|
||||||
|
}
|
||||||
|
|
||||||
|
return '/' + suffix;
|
||||||
}
|
}
|
||||||
|
|
||||||
private async Task ProcessRequestAsync(HttpListenerContext ctx) {
|
private async Task ProcessRequestAsync(HttpListenerContext ctx) {
|
||||||
@@ -262,8 +268,9 @@ public sealed class HttpServer {
|
|||||||
/* Finding the endpoint that should process the request:
|
/* Finding the endpoint that should process the request:
|
||||||
* 1. Try to see if there is a simple endpoint where request method and path match
|
* 1. Try to see if there is a simple endpoint where request method and path match
|
||||||
* 2. Otherwise, try to see if a path-parameter-endpoint matches (duplicates throw an error on startup)
|
* 2. Otherwise, try to see if a path-parameter-endpoint matches (duplicates throw an error on startup)
|
||||||
* 3. Otherwise, check if it is inside a static serve path
|
* 3. Otherwise, check if wildcardFallbackHandlers contains a handler for the current requestMethod. If this method returns false 'request was not handled', continue, otherwise skip all future steps.
|
||||||
* 4. Otherwise, show 404 page */
|
* 4. Otherwise, check if it is inside a static serve path
|
||||||
|
* 5. Otherwise, show 404 page */
|
||||||
|
|
||||||
EndpointInvocationInfo? pathEndpointInvocationInfo = null;
|
EndpointInvocationInfo? pathEndpointInvocationInfo = null;
|
||||||
if (simpleEndpointMethodInfos.TryGetValue(requestMethod, reqPath, out var simpleEndpointInvocationInfo) ||
|
if (simpleEndpointMethodInfos.TryGetValue(requestMethod, reqPath, out var simpleEndpointInvocationInfo) ||
|
||||||
@@ -328,10 +335,18 @@ public sealed class HttpServer {
|
|||||||
var splittedReqPath = reqPath[1..].Split('/');
|
var splittedReqPath = reqPath[1..].Split('/');
|
||||||
for (int i = 0; i < pparams.Count; i++) {
|
for (int i = 0; i < pparams.Count; i++) {
|
||||||
var pparam = pparams[i];
|
var pparam = pparams[i];
|
||||||
|
string paramValue;
|
||||||
if (pparam.IsCatchAll)
|
if (pparam.IsCatchAll)
|
||||||
convertedMParamValues[pparam.ArgPos] = string.Join('/', splittedReqPath[pparam.SegmentStartPos..]);
|
paramValue = string.Join('/', splittedReqPath[pparam.SegmentStartPos..]);
|
||||||
else
|
else
|
||||||
convertedMParamValues[pparam.ArgPos] = splittedReqPath[pparam.SegmentStartPos];
|
paramValue = splittedReqPath[pparam.SegmentStartPos];
|
||||||
|
|
||||||
|
if (stringToTypeParameterConverters[pparam.Type].TryConvertFromString(paramValue, out var res))
|
||||||
|
convertedMParamValues[pparam.ArgPos] = res;
|
||||||
|
else {
|
||||||
|
await HandleDefaultErrorPageAsync(rc, HttpStatusCode.BadRequest);
|
||||||
|
return;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -341,7 +356,17 @@ public sealed class HttpServer {
|
|||||||
// todo read and convert pathparams
|
// todo read and convert pathparams
|
||||||
|
|
||||||
await (Task) (mi.Invoke(endpointInvocationInfo.typeInstanceReference, convertedMParamValues) ?? throw new NullReferenceException("Website func returned null unexpectedly"));
|
await (Task) (mi.Invoke(endpointInvocationInfo.typeInstanceReference, convertedMParamValues) ?? throw new NullReferenceException("Website func returned null unexpectedly"));
|
||||||
} else { // try to find suitable static serve path
|
} else {
|
||||||
|
// ---------------- check for fallback wildcard handler ----------------
|
||||||
|
if (wildcardFallbackHandlers.TryGetValue(requestMethod, out var handler)) {
|
||||||
|
var handledByWildcard = await handler.Invoke(rc);
|
||||||
|
if (handledByWildcard) { // if that handler was able to handle the request, end execution
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// ---------------------------------------------------------------------
|
||||||
|
|
||||||
|
// try to find suitable static serve path
|
||||||
if (requestMethod == "GET")
|
if (requestMethod == "GET")
|
||||||
foreach (var (k, v) in staticServePaths) {
|
foreach (var (k, v) in staticServePaths) {
|
||||||
if (reqPath.StartsWith(k)) { // do a static serve
|
if (reqPath.StartsWith(k)) { // do a static serve
|
||||||
@@ -402,4 +427,14 @@ public sealed class HttpServer {
|
|||||||
}
|
}
|
||||||
} catch (ObjectDisposedException) { }
|
} catch (ObjectDisposedException) { }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Adds a wildcard fallback handler that receives any request that was not matched by a more explicit endpoint.
|
||||||
|
/// The handler is supposed to return 'true' if the request was handled correctly and thus execution shall end. Return 'false' to try to serve the file from a static-serve path.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="reqMethod"></param>
|
||||||
|
/// <param name="requestHandler">This method must return whether the reuqest was handled; returning false makes handling act as if this handler never ran</param>
|
||||||
|
public void RegisterWildcardFallbackHandler(HttpRequestType reqMethod, Func<RequestContext, Task<bool>> requestHandler) {
|
||||||
|
wildcardFallbackHandlers.Add(Enum.GetName(reqMethod) ?? throw new NotImplementedException(), requestHandler);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -13,6 +13,10 @@ public class SimpleHttpServerConfiguration {
|
|||||||
/// See description of <see cref="DisableLogMessagePrinting"/>
|
/// See description of <see cref="DisableLogMessagePrinting"/>
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public CustomLogMessageHandler? LogMessageHandler { get; init; } = null;
|
public CustomLogMessageHandler? LogMessageHandler { get; init; } = null;
|
||||||
|
/// <summary>
|
||||||
|
/// If set to true, paths ending with / are identical to paths without said trailing slash. E.g. /index is then the same as /index/
|
||||||
|
/// </summary>
|
||||||
|
public bool TrimTrailingSlash { get; init; } = true;
|
||||||
|
|
||||||
public SimpleHttpServerConfiguration() { }
|
public SimpleHttpServerConfiguration() { }
|
||||||
|
|
||||||
|
|||||||
@@ -22,12 +22,12 @@ internal class PathTree<T> where T : class {
|
|||||||
throw new Exception($"Found illegal catchall-wildcard in path: '{string.Join('/', path)}'");
|
throw new Exception($"Found illegal catchall-wildcard in path: '{string.Join('/', path)}'");
|
||||||
}
|
}
|
||||||
|
|
||||||
var leafdata = unpackedLeafData[i];
|
var leafdata = unpackedLeafData[i] ?? throw new ArgumentNullException("Leafdata must not be null!");
|
||||||
rootNode.AddSuccessor(path, leafdata);
|
rootNode.AddSuccessor(path, leafdata);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
internal bool TryGetPath(string reqPath, [MaybeNullWhen(false)] out T? endpoint) {
|
internal bool TryGetPath(string reqPath, [MaybeNullWhen(false)] out T endpoint) {
|
||||||
if (rootNode == null) {
|
if (rootNode == null) {
|
||||||
endpoint = null;
|
endpoint = null;
|
||||||
return false;
|
return false;
|
||||||
@@ -58,16 +58,16 @@ internal class PathTree<T> where T : class {
|
|||||||
|
|
||||||
// return found path
|
// return found path
|
||||||
endpoint = currNode.leafData;
|
endpoint = currNode.leafData;
|
||||||
return true;
|
return endpoint != null;
|
||||||
}
|
}
|
||||||
|
|
||||||
private class Node {
|
private class Node {
|
||||||
public T? leafData = null;
|
public T? leafData = null; // null means that this is a node without a value (e.g. when it is just part of a path)
|
||||||
public Dictionary<string, Node>? next = null;
|
public Dictionary<string, Node>? next = null;
|
||||||
public Node? pathWildcardNext = null; // path wildcard
|
public Node? pathWildcardNext = null; // path wildcard
|
||||||
public Node? catchAllNext = null; // trailing-catchall wildcard
|
public Node? catchAllNext = null; // trailing-catchall wildcard
|
||||||
|
|
||||||
public void AddSuccessor(string[] segments, T? newLeafData) {
|
public void AddSuccessor(string[] segments, T newLeafData) {
|
||||||
if (segments.Length == 0) { // actually add the data to this node
|
if (segments.Length == 0) { // actually add the data to this node
|
||||||
Assert(leafData == null);
|
Assert(leafData == null);
|
||||||
leafData = newLeafData;
|
leafData = newLeafData;
|
||||||
@@ -84,17 +84,14 @@ internal class PathTree<T> where T : class {
|
|||||||
catchAllNext.AddSuccessor(segments[1..], newLeafData);
|
catchAllNext.AddSuccessor(segments[1..], newLeafData);
|
||||||
return;
|
return;
|
||||||
} else { // must be single wildcard otherwise
|
} else { // must be single wildcard otherwise
|
||||||
Assert(pathWildcardNext == null);
|
pathWildcardNext ??= new();
|
||||||
pathWildcardNext = new();
|
|
||||||
pathWildcardNext.AddSuccessor(segments[1..], newLeafData);
|
pathWildcardNext.AddSuccessor(segments[1..], newLeafData);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// otherwise we want to add a new constant path successor
|
// otherwise we want to add a new constant path successor
|
||||||
if (next == null) {
|
next ??= new();
|
||||||
next = new();
|
|
||||||
}
|
|
||||||
|
|
||||||
if (next.TryGetValue(seg, out var existingNode)) {
|
if (next.TryGetValue(seg, out var existingNode)) {
|
||||||
existingNode.AddSuccessor(segments[1..], newLeafData);
|
existingNode.AddSuccessor(segments[1..], newLeafData);
|
||||||
|
|||||||
@@ -35,22 +35,23 @@ public class RequestContext : IDisposable {
|
|||||||
|
|
||||||
public void SetStatusCode(HttpStatusCode status) => SetStatusCode((int) status);
|
public void SetStatusCode(HttpStatusCode status) => SetStatusCode((int) status);
|
||||||
|
|
||||||
|
public async Task SetStatusCodeWriteLineDisposeAsync(HttpStatusCode status, string message) {
|
||||||
|
SetStatusCode(status);
|
||||||
|
await WriteLineToRespAsync(message);
|
||||||
|
await RespWriter.FlushAsync();
|
||||||
|
}
|
||||||
|
|
||||||
public async Task SetStatusCodeAndDisposeAsync(int status) {
|
public async Task SetStatusCodeAndDisposeAsync(int status) {
|
||||||
using (this) {
|
using (this) {
|
||||||
SetStatusCode(status);
|
SetStatusCode(status);
|
||||||
|
if (status != (int)HttpStatusCode.NotModified) { // NotModified must not write any data to response
|
||||||
await WriteToRespAsync("\n\n");
|
await WriteToRespAsync("\n\n");
|
||||||
await RespWriter.FlushAsync();
|
await RespWriter.FlushAsync();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task SetStatusCodeAndDisposeAsync(HttpStatusCode status) {
|
|
||||||
using (this) {
|
|
||||||
SetStatusCode((int) status);
|
|
||||||
await WriteToRespAsync("\n\n");
|
|
||||||
await RespWriter.FlushAsync();
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public async Task SetStatusCodeAndDisposeAsync(HttpStatusCode status) => await SetStatusCodeAndDisposeAsync((int) status);
|
||||||
|
|
||||||
public async Task SetStatusCodeAndDisposeAsync(int status, string description) {
|
public async Task SetStatusCodeAndDisposeAsync(int status, string description) {
|
||||||
using (this) {
|
using (this) {
|
||||||
|
|||||||
Reference in New Issue
Block a user