From 58ca6d6119ed77f8c1d564bac109fc36db10e3d0 Mon Sep 17 00:00:00 2001 From: Peter Kieltyka Date: Sat, 21 Oct 2023 20:41:35 -0400 Subject: [PATCH] middleware: new SupressNotFound handler --- middleware/supress_notfound.go | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 middleware/supress_notfound.go diff --git a/middleware/supress_notfound.go b/middleware/supress_notfound.go new file mode 100644 index 00000000..83a8a872 --- /dev/null +++ b/middleware/supress_notfound.go @@ -0,0 +1,27 @@ +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(rctx, r.Method, r.URL.Path) + if !match { + router.NotFoundHandler().ServeHTTP(w, r) + return + } + next.ServeHTTP(w, r) + }) + } +}