oapi-codegen
oapi-codegen copied to clipboard
Chi middleware wrapping logic executes the beginning middlewares at the later part
Current implementation server middlewares to a handler goes like this:
var handler = func(w http.ResponseWriter, r *http.Request) {
siw.Handler.YourRouteHandler(w, r)
}
for _, middleware := range siw.HandlerMiddlewares {
handler = middleware(handler)
}
The snippet above tends to execute beginning middlewares at the later than the last ones.
The looping is supposed to be like this:
var handler = func(w http.ResponseWriter, r *http.Request) {
siw.Handler.YourRouteHandler(w, r)
}
for i := len(siw.HandlerMiddlewares) - 1; i >= 0; i-- {
h := siw.HandlerMiddlewares[i]
if h != nil {
handler = h(handler)
}
}
The solution is referenced from Ardan Lab's Service repository on wrapping middlewares
Here is the source from chi:
// chain builds a http.Handler composed of an inline middleware stack and endpoint
// handler in the order they are passed.
func chain(middlewares []func(http.Handler) http.Handler, endpoint http.Handler) http.Handler {
// Return ahead of time if there aren't any middlewares for the chain
if len(middlewares) == 0 {
return endpoint
}
// Wrap the end handler with the middleware chain
h := middlewares[len(middlewares)-1](endpoint)
for i := len(middlewares) - 2; i >= 0; i-- {
h = middlewares[i](h)
}
return h
}
https://github.com/go-chi/chi/blob/9db25e5b381fbd6350583b857e74ecaffe355819/chain.go#L34-L49
This should now be supported in the next release (including this PR) using the following options in your config YAML:
compatibility:
apply-chi-middleware-first-to-last: true
This issue can be closed (but I don't have permissions to close it).