suborbital / vektor

Opinionated production-grade HTTP server framework for Go
Apache License 2.0
82 stars 8 forks source link

Make middlewares wrap handlers rather than run before and after #79

Closed javorszky closed 2 years ago

javorszky commented 2 years ago

Currently middlewares and afterwares are handled in the vk/middleware.go file augmentHandler method. The way this works is that it calls the middlewares first, one by one, and finishes with them, then calls the actual core handler function, and then calls a bunch of other afterwares, one by one.

An architecture diagram would look like this:

Request -> (mw1) -> (mw2) -> (core handler) -> (aw1) -> (aw2) -> Response

Instead middlewares should be wrapping the other handlers. That way we can construct a layered structure that simplifies code and is easier to reason about, plus it would remove distinction between a middleware (used here to mean running code that should happen before the core handler does anything with it), and afterware (used here to mean running code that should happen after the core handler is done with the request).

The target structure should look like this:

Request ->                                                                                      -> Response
           ( mw1 ->                                                    -> mw1, but after code )
                    ( mw2 ->                  -> mw2, but after code )
                             ( core handler )
javorszky commented 2 years ago

A 💎 : https://justinas.org/alice-painless-middleware-chaining-for-go