Skip to content

Chi-server wrapping middleware logic fix. - #688

Closed
juddbaguio wants to merge 1 commit into
oapi-codegen:masterfrom
juddbaguio:wrapping-middleware-logic-fix-(chi-server)
Closed

juddbaguio wants to merge 1 commit into
oapi-codegen:masterfrom
juddbaguio:wrapping-middleware-logic-fix-(chi-server)

Conversation

@juddbaguio

Copy link
Copy Markdown

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 juddbaguio changed the title Wrapping middleware logic fix. Chi-server wrapping middleware logic fix. Jul 20, 2022
@ghost

ghost commented Jul 25, 2022

Copy link
Copy Markdown

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

@juddbaguio

Copy link
Copy Markdown
Author

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.

@uhey22e

uhey22e commented Sep 3, 2022 •

Copy link
Copy Markdown
Contributor

+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

@jamietanna

Copy link
Copy Markdown
Member

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants