-
-
Notifications
You must be signed in to change notification settings - Fork 988
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
middleware: new SupressNotFound handler
- Loading branch information
Showing
1 changed file
with
27 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -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) | ||
}) | ||
} | ||
} |