Skip to content

Commit

Permalink
Merge pull request #6 from stifskere/dev
Browse files Browse the repository at this point in the history
feat: middleware structure
  • Loading branch information
stifskere authored Apr 11, 2024
2 parents e785d38 + ae03cf8 commit cec1895
Show file tree
Hide file tree
Showing 7 changed files with 57 additions and 64 deletions.
4 changes: 2 additions & 2 deletions MemwLib.sln.DotSettings.user
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
<wpf:ResourceDictionary xml:space="preserve" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:s="clr-namespace:System;assembly=mscorlib" xmlns:ss="urn:shemas-jetbrains-com:settings-storage-xaml" xmlns:wpf="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
<s:String x:Key="/Default/CodeInspection/Highlighting/SweaWarningsMode/@EntryValue">ShowAndRun</s:String>
<s:String x:Key="/Default/Environment/UnitTesting/UnitTestSessionStore/Sessions/=7db57a97_002D6769_002D46f2_002D8c33_002D861038889f31/@EntryIndexedValue">&lt;SessionState ContinuousTestingMode="0" IsActive="True" Name="Cookies" xmlns="urn:schemas-jetbrains-com:jetbrains-ut-session"&gt;&#xD;
&lt;Solution /&gt;&#xD;
<s:String x:Key="/Default/Environment/UnitTesting/UnitTestSessionStore/Sessions/=7db57a97_002D6769_002D46f2_002D8c33_002D861038889f31/@EntryIndexedValue">&lt;SessionState ContinuousTestingMode="0" IsActive="True" Name="Cookies" xmlns="urn:schemas-jetbrains-com:jetbrains-ut-session"&gt;
&lt;Solution /&gt;
&lt;/SessionState&gt;</s:String>


Expand Down
12 changes: 6 additions & 6 deletions MemwLib/Http/HttpServer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -182,8 +182,8 @@ private void ThreadHandler()
HeaderCollection headerCache = new();

RunMiddleware(_globalMiddleware);
RunMiddlewareFromAttributes(handler.Method.DeclaringType?.GetCustomAttributes<UsesMiddlewareAttribute>());
RunMiddlewareFromAttributes(handler.Method.GetCustomAttributes<UsesMiddlewareAttribute>());
RunMiddlewareFromAttributes(handler.Method.DeclaringType?.GetCustomAttributes<MiddlewareAttribute>());
RunMiddlewareFromAttributes(handler.Method.GetCustomAttributes<MiddlewareAttribute>());

responseEntity ??= handler(parsedRequest)
.WithHeaders(headerCache);
Expand Down Expand Up @@ -211,14 +211,14 @@ void RunMiddleware(IEnumerable<MiddleWareDelegate>? middleWarePieces)
}
}

void RunMiddlewareFromAttributes(IEnumerable<UsesMiddlewareAttribute>? middlewarePieces)
void RunMiddlewareFromAttributes(IEnumerable<MiddlewareAttribute>? middlewarePieces)
{
if (middlewarePieces is null)
return;

foreach (UsesMiddlewareAttribute middleware in middlewarePieces)
foreach (MiddlewareAttribute middleware in middlewarePieces)
{
next = middleware.Target(parsedRequest);
next = middleware.Handler(parsedRequest);

headerCache.Add(next.Headers);

Expand Down Expand Up @@ -357,7 +357,7 @@ public HttpServer AddGroup(Type type)

foreach (MethodInfo method in type.GetMethods(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.ExactBinding))
{
GroupMemberAttribute? postFix = method.GetCustomAttribute<GroupMemberAttribute>();
RouteAttribute? postFix = method.GetCustomAttribute<RouteAttribute>();

if (postFix is null)
continue;
Expand Down
24 changes: 24 additions & 0 deletions MemwLib/Http/Types/Attributes/MiddlewareAttribute.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
using JetBrains.Annotations;
using MemwLib.Http.Types.Entities;

namespace MemwLib.Http.Types.Attributes;

/// <summary>
/// Base middleware class, every class extending this
/// one will be counted as middleware within the HTTPServer
/// </summary>
[PublicAPI]
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true)]
public abstract class MiddlewareAttribute : Attribute
{
/// <summary>
/// This method will be ran every time a route
/// or route group with this middleware is called.
/// </summary>
/// <param name="request">The incoming request from the server.</param>
/// <returns>
/// A ResponseEntity to end the request or a NextMiddleware instance
/// telling the server to call the next corresponding handler for this request.
/// </returns>
public abstract IResponsible Handler(RequestEntity request);
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ namespace MemwLib.Http.Types.Attributes;

/// <summary>Defines a group member that forms part of a route group.</summary>
[AttributeUsage(AttributeTargets.Method), UsedImplicitly]
public sealed class GroupMemberAttribute : Attribute
public sealed class RouteAttribute : Attribute
{
internal string Route { get; }

Expand All @@ -21,7 +21,7 @@ public sealed class GroupMemberAttribute : Attribute
/// RouteGroupAttribute, will define the route from root.
/// BEWARE THE ROUTES SHOULD MATCH, IF THE GROUP MEMBER ENDS WITH / AND THIS STARTS WITH / IT WILL TRY TO MATCH //
/// </remarks>
public GroupMemberAttribute(RequestMethodType requestMethod, string route, bool asRegex = false)
public RouteAttribute(RequestMethodType requestMethod, string route, bool asRegex = false)
{
RequestMethod = requestMethod;
Route = route;
Expand Down
42 changes: 0 additions & 42 deletions MemwLib/Http/Types/Attributes/UsesMiddlewareAttribute.cs

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,21 @@ namespace MemwLib.Http.Types.Entities;

/// <summary>Tells the server to execute the next middleware piece.</summary>
[PublicAPI]
public sealed class NextMiddleWare : IResponsible
public sealed class Middleware : IResponsible
{
/// <summary>
/// Creates a new instance of "Middleware" which lets you
/// specify options to pass to the next handler.
/// </summary>
public static Middleware Next => new();

internal Middleware() {}

/// <inheritdoc cref="IResponsible.Headers"/>
public HeaderCollection Headers { get; set; } = new();

/// <inheritdoc cref="IResponsible.WithHeader"/>
public NextMiddleWare WithHeader(string key, string value)
public Middleware WithHeader(string key, string value)
{
Headers.Add(key, value);
return this;
Expand All @@ -21,7 +29,7 @@ IResponsible IResponsible.WithHeader(string key, string value)
=> WithHeader(key, value);

/// <inheritdoc cref="IResponsible.WithHeaders(Dictionary{string, string})"/>
public NextMiddleWare WithHeaders(Dictionary<string, string> headers)
public Middleware WithHeaders(Dictionary<string, string> headers)
{
Headers.Add(headers);
return this;
Expand All @@ -31,7 +39,7 @@ IResponsible IResponsible.WithHeaders(Dictionary<string, string> headers)
=> WithHeaders(headers);

/// <inheritdoc cref="IResponsible.WithHeaders(HeaderCollection)"/>
public NextMiddleWare WithHeaders(HeaderCollection headers)
public Middleware WithHeaders(HeaderCollection headers)
{
Headers.Add(headers);
return this;
Expand Down
19 changes: 11 additions & 8 deletions Tests/Http.cs
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@ public void Setup()
_server.AddGroup<RoutesFromClass>();

_server.AddEndpoint(RequestMethodType.Options, new Regex(".+"), _ => new ResponseEntity(ResponseCodes.Ok));
_server.AddGlobalMiddleware(_ => new NextMiddleWare().WithHeader("Access-Control-Allow-Origin", "*"));
_server.AddGlobalMiddleware(_ => Middleware.Next.WithHeader("Access-Control-Allow-Origin", "*"));
}

[Test]
Expand Down Expand Up @@ -197,17 +197,20 @@ public void Dispose()
}
}

[RouteGroup("/header-test")]
public class RoutesFromClass
public class AddHeaderMiddlewareAttribute(string value) : MiddlewareAttribute
{
public static IResponsible AddHeaderMiddleware(RequestEntity _)
public override IResponsible Handler(RequestEntity request)
{
return new NextMiddleWare()
.WithHeader("My-Header-From-Middleware", "true");
return Middleware.Next
.WithHeader("My-Header-From-Middleware", value);
}
}

[UsesMiddleware(typeof(RoutesFromClass), nameof(AddHeaderMiddleware))]
[GroupMember(RequestMethodType.Get, "/uhh"), UsedImplicitly]
[RouteGroup("/header-test")]
public class RoutesFromClass
{
[AddHeaderMiddleware("true")]
[Route(RequestMethodType.Get, "/uhh"), UsedImplicitly]
public static ResponseEntity TestHeader(RequestEntity _)
{
return new ResponseEntity(ResponseCodes.Ok)
Expand Down

0 comments on commit cec1895

Please sign in to comment.