Huge refactor; Passing tests
This commit is contained in:
@@ -8,13 +8,13 @@ namespace SimpleHttpServer.Internal;
|
||||
internal class HttpEndpointHandler {
|
||||
private static readonly DefaultAuthorizer defaultAuth = new();
|
||||
|
||||
private readonly IAuthorizer _auth;
|
||||
private readonly MethodInfo _handler;
|
||||
private readonly Dictionary<string, (int pindex, Type type, int pparamIdx)> _params;
|
||||
private readonly Func<Exception, HttpResponseBuilder> _errorPageBuilder;
|
||||
private readonly IAuthorizer auth;
|
||||
private readonly MethodInfo handler;
|
||||
private readonly Dictionary<string, (int pindex, Type type, int pparamIdx)> @params;
|
||||
private readonly Func<Exception, HttpResponseBuilder> errorPageBuilder;
|
||||
|
||||
public HttpEndpointHandler() {
|
||||
_auth = defaultAuth;
|
||||
auth = defaultAuth;
|
||||
}
|
||||
|
||||
public HttpEndpointHandler(IAuthorizer auth) {
|
||||
@@ -23,14 +23,14 @@ internal class HttpEndpointHandler {
|
||||
|
||||
public virtual void Handle(HttpListenerContext ctx) {
|
||||
try {
|
||||
var (isAuth, authData) = _auth.IsAuthenticated(ctx);
|
||||
var (isAuth, authData) = auth.IsAuthenticated(ctx);
|
||||
if (!isAuth) {
|
||||
throw new HttpHandlingException(401, "Authorization required!");
|
||||
}
|
||||
|
||||
// collect parameters
|
||||
var invokeParams = new object?[_params.Count + 1];
|
||||
var set = new BitArray(_params.Count);
|
||||
var invokeParams = new object?[@params.Count + 1];
|
||||
var set = new BitArray(@params.Count);
|
||||
invokeParams[0] = ctx;
|
||||
|
||||
// read pparams
|
||||
@@ -38,8 +38,8 @@ internal class HttpEndpointHandler {
|
||||
// read qparams
|
||||
var qst = ctx.Request.QueryString;
|
||||
foreach (var qelem in ctx.Request.QueryString.AllKeys) {
|
||||
if (_params.ContainsKey(qelem!)) {
|
||||
var (pindex, type, isPParam) = _params[qelem!];
|
||||
if (@params.ContainsKey(qelem!)) {
|
||||
var (pindex, type, isPParam) = @params[qelem!];
|
||||
if (type == typeof(string)) {
|
||||
invokeParams[pindex] = ctx.Request.QueryString[qelem!];
|
||||
set.Set(pindex - 1, true);
|
||||
@@ -54,20 +54,20 @@ internal class HttpEndpointHandler {
|
||||
}
|
||||
|
||||
// fill with defaults
|
||||
foreach (var p in _params) {
|
||||
foreach (var p in @params) {
|
||||
if (!set.Get(p.Value.pindex)) {
|
||||
invokeParams[p.Value.pindex] = p.Value.type.IsValueType ? Activator.CreateInstance(p.Value.type) : null;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
var builder = _handler.Invoke(null, invokeParams) as HttpResponseBuilder;
|
||||
var builder = handler.Invoke(null, invokeParams) as HttpResponseBuilder;
|
||||
builder!.SendResponse(ctx.Response);
|
||||
} catch (Exception e) {
|
||||
if (e is TargetInvocationException tex) {
|
||||
e = tex.InnerException!;
|
||||
}
|
||||
_errorPageBuilder(e).SendResponse(ctx.Response);
|
||||
errorPageBuilder(e).SendResponse(ctx.Response);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user