oapi-codegen
oapi-codegen copied to clipboard
Chi-server wrapping middleware logic fix.
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
Hmm, interesting, so we process them in reverse order. This will reverse processing order for anyone who regenerates their code.
Exactly, we need to execute the right order of middlewares, this might also cause confusion to the devs who came from the Node.js background.
+1
FYI,
Chi reverse the order of middlewares as like as this PR when you use (*chi.Mux).Use()
.
https://github.com/go-chi/chi/blob/0316d5a1df8598eceb137f5f77945be56810b564/chain.go#L42
Thanks for this, looks like we got it finished in #787!