SupressNotFound ran its preflight Match on the live route context. Match
descends into mounted subrouters and rewrites RoutePath and URLParams, so
the following dispatch routed the mount's suffix against the root router:
- mounted routes returned 404, or were served by a root route with the
same suffix, skipping the subrouter's middleware (GHSA-rqrp-8cg2-5958)
- on all routes, URLParams and RoutePatterns were recorded twice, so
RoutePattern() returned e.g. "/users/{id}/users/{id}"
Match on a fresh route context instead, like GetHead already does.
Co-authored-by: Claude Haiku 5.5 <noreply@anthropic.com>
27 lines
869 B
Go
27 lines
869 B
Go
package middleware
|
|
|
|
import (
|
|
"net/http"
|
|
|
|
"github.com/go-chi/chi/v5"
|
|
)
|
|
|
|
// SupressNotFound will quickly respond with a 404 if the route is not found
|
|
// and will not continue to the next middleware handler.
|
|
//
|
|
// This is handy to put at the top of your middleware stack to avoid unnecessary
|
|
// processing of requests that are not going to match any routes anyway. For
|
|
// example its super annoying to see a bunch of 404's in your logs from bots.
|
|
func SupressNotFound(router *chi.Mux) func(next http.Handler) http.Handler {
|
|
return func(next http.Handler) http.Handler {
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
rctx := chi.RouteContext(r.Context())
|
|
match := rctx.Routes.Match(chi.NewRouteContext(), r.Method, r.URL.Path)
|
|
if !match {
|
|
router.NotFoundHandler().ServeHTTP(w, r)
|
|
return
|
|
}
|
|
next.ServeHTTP(w, r)
|
|
})
|
|
}
|
|
}
|