alec1o / Netly

Netly: Cross-Platform, Multi-Protocol C# Socket Library ā€“ Fast, Easy, and Versatile.āš”
https://netly.docs.kezero.com
MIT License
67 stars 11 forks source link

Body Parser as Middleware #67

Open alec1o opened 1 month ago

alec1o commented 1 month ago

Description:

HTTP.Body.Enctype is already detected and saved, allowing us to simplify parsing the body content. The method HTTP.Body.Parse<T>() will use this detected enctype to automatically parse the content. HTTP.Body.OnParse(HTTP.Enctype enctype, bool replaceOnMatch, Func<Type, object>) Used to set parser configuration.

Key Points:

Benefits:

Example Usage:

var server = new HTTP.Server();

server.Map.Post("/", (request, response) =>
{
    var user = request.Body.Parse<CreateUserDTO>();
    if (user == null) return response.Send(400, "{'message': 'invalid body'}");
    return response.Send(201);
});

server.To.Open(new Uri("https://127.0.0.1:8080"));

Usage middleware to parse HTTP.Body

var server = new HTTP.Server();

server.Middleware.Add((request, response, next) =>
{
    var text = request.Body.Text;

    // .NET 6+, also can use Json.NET (Newtonsoft Json)  or others implementation
    // Adding JSON Enctype parser
    request.Body.OnParse(HTTP.Enctype.Json, false, (type) => JsonSerializer.Deserialize(text, type, JsonSerializerOptions.Default));

    // Adding YAML Enctype parser
    request.Body.OnParse(HTTP.Enctype.Yml, false, (type) => Example.Method(text, type, ExampleOptions.Default));

    // Adding XML Enctype parser
    request.Body.OnParse(HTTP.Enctype.Xml, false, (type) => Example.Method(text, type, ExampleOptions.Default));

    ...   

    next();
});

server.To.Open(new Uri("https://127.0.0.1:8080"));
alec1o commented 1 month ago

Solved at: 6a793924e344cc3fdbdb18b77b5837027d576c24

alec1o commented 1 month ago

I @ale1o @aleciofuranze (Alecio Furanze) Currently, there are no built-in parsers for Enctype, but the mechanism to implement middleware for parsing is already in place. In future versions, we will add built-in parsers for Enctypes such as JSON, XML, and YAML. This will reduce the need to manually create Enctype parsers to process the request body. However, even after the addition of these integrated parsers, you can still choose to use a more sophisticated parser, and the library will continue to support these parsing options via middleware in case you need to parse unsupported Enctypes or for any other reason. The key difference is that the built-in parsers will be available by default.

Enctype Status
šŸŒ UrlEncoded ā³ Planned
šŸ“‚ Multipart ā³ Planned
šŸ“„ Json ā³ Planned
šŸ“œ Yaml ā³ Planned
šŸ—‚ļø Xml ā³ Planned
šŸ“Š Csv ā³ Planned
āš›ļø GraphQL ā³ Planned
šŸ“¦ SoapXml ā³ Planned
šŸ“ MultipartRelated ā³ Planned

Notes: