oapi-codegen icon indicating copy to clipboard operation
oapi-codegen copied to clipboard

Chi-server wrapping middleware logic fix.

Open juddbaguio opened this issue 2 years ago • 3 comments

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

juddbaguio avatar Jul 20 '22 00:07 juddbaguio

Hmm, interesting, so we process them in reverse order. This will reverse processing order for anyone who regenerates their code.

deepmap-marcinr avatar Jul 25 '22 19:07 deepmap-marcinr

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.

juddbaguio avatar Jul 25 '22 23:07 juddbaguio

+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

uhey22e avatar Sep 03 '22 06:09 uhey22e

Thanks for this, looks like we got it finished in #787!

jamietanna avatar Nov 12 '22 21:11 jamietanna