Question/Feature Request - Adding a "use" method to Router
Manghud opened this issue · comments
Hello. I really like this project. I would like to request to add a method to apply middleware to a whole group/router. I'm willing to contribute if needed
@savsgio I'm not sure this is possible to implement by wrapping the handler if you want to add middleware before the routes but after the router's built-in redirection/HandleMethodNotAllowed
middleware. For example, if I wrap the handler like this:
r := router.New()
r.RedirectTrailingSlash = true
r.RedirectFixedPath = true
r.HandleMethodNotAllowed = true
r.GET("/hello", helloHandler)
fasthttp.ListenAndServe(":8080", func(ctx *fasthttp.RequestContext) {
// my middleware here
r.Handler(ctx)
})
The order of execution for a request to /hello
is this:
- my middleware wrapper function
router
'sRedirectTrailingSlash
,RedirectFixedPath
, andHandleMethodNotAllowed
logichelloHandler
What I would like is the ability to run them in this order:
router
'sRedirectTrailingSlash
,RedirectFixedPath
, andHandleMethodNotAllowed
logic- my middleware wrapper function
helloHandler
If I understand correctly, this is only possible with a Use
method or something similar, like @Manghud described, right? This is important to me because my middleware in this use case that runs on every route needs to hit the database (load a session, for example). I do not want to hit the database for simple redirects and method-not-allowed responses.
Additionally, without a Use
method on Group
s, I don't think it is possible to apply middleware specifically to a group.
Hi @winduptoy,
Sorry for delayed answer.
If you want thats behaviour, you must wrap the helloHandler
and not execute the middleware before the r.Handler
.
So if you need a simple API to use middlewares, you could use some of frameworks built on top of fasthttp.