supress_notfound.go 852 B

123456789101112131415161718192021222324252627
  1. package middleware
  2. import (
  3. "net/http"
  4. "github.com/go-chi/chi/v5"
  5. )
  6. // SupressNotFound will quickly respond with a 404 if the route is not found
  7. // and will not continue to the next middleware handler.
  8. //
  9. // This is handy to put at the top of your middleware stack to avoid unnecessary
  10. // processing of requests that are not going to match any routes anyway. For
  11. // example its super annoying to see a bunch of 404's in your logs from bots.
  12. func SupressNotFound(router *chi.Mux) func(next http.Handler) http.Handler {
  13. return func(next http.Handler) http.Handler {
  14. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  15. rctx := chi.RouteContext(r.Context())
  16. match := rctx.Routes.Match(rctx, r.Method, r.URL.Path)
  17. if !match {
  18. router.NotFoundHandler().ServeHTTP(w, r)
  19. return
  20. }
  21. next.ServeHTTP(w, r)
  22. })
  23. }
  24. }