go-chi / chi

lightweight, idiomatic and composable router for building Go HTTP services
https://go-chi.io
MIT License
18.2k stars 980 forks source link

Middleware Chaining Not Respected by NotFound Handler #837

Open sethgrid opened 1 year ago

sethgrid commented 1 year ago

I'm trying to set up a "catch all" route. Anything that goes to "catchall/some/other/thing" should go the allHandler. I have values that I am setting onto the context in my middleware. These values ONLY show up if I use r.HandleFunc("/", allHandler ) - if I only use the NotFound handler, then the middleware is never set.

router := chi.NewRouter()
router.Route("/catchall", func(r chi.Router) {
  r.Use(MiddlewareSetsContextValues)
  r.NotFound(allHandler)
  // uncomment the following so it works
  // r.HandleFunc("/", allHandler) // wont match ../some/other/thing
})

This feels like a bug - I'd have expected the r.HandleFunc to not be needed to register the middleware.

pkieltyka commented 1 year ago

yes, this I’ve seen this confusion in the past — which is that at least one handler must be defined on a router for it to build the middleware stack.