From 1ddce43e979165817145f70d71095e37ce774d9a Mon Sep 17 00:00:00 2001 From: Tuan Nguyen Date: Thu, 20 Feb 2020 20:58:46 +0800 Subject: [PATCH] Add a flag to require explicit method not allowed handler --- mux.go | 5 ++++- mux_test.go | 17 +++++++++++++++++ 2 files changed, 21 insertions(+), 1 deletion(-) diff --git a/mux.go b/mux.go index c9ba647..ac913f1 100644 --- a/mux.go +++ b/mux.go @@ -51,6 +51,9 @@ type Router struct { // Configurable Handler to be used when the request method does not match the route. MethodNotAllowedHandler http.Handler + // If true, only handle MethodNotAllowed if the router MethodNotAllowedHandler is explicitly specified + RequireExplicitMethodNotAllowedHandler bool + // Routes to be matched, in order. routes []*Route @@ -199,7 +202,7 @@ func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request) { req = requestWithRoute(req, match.Route) } - if handler == nil && match.MatchErr == ErrMethodMismatch { + if handler == nil && match.MatchErr == ErrMethodMismatch && !r.RequireExplicitMethodNotAllowedHandler { handler = methodNotAllowedHandler() } diff --git a/mux_test.go b/mux_test.go index 2d8d2b3..8183c84 100644 --- a/mux_test.go +++ b/mux_test.go @@ -2733,6 +2733,23 @@ func TestMethodNotAllowed(t *testing.T) { } } +func TestRequireExplicitMethodNotAllowedHandler(t *testing.T) { + handler := func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) } + router := NewRouter() + router.RequireExplicitMethodNotAllowedHandler = true + router.HandleFunc("/thing", handler).Methods(http.MethodGet) + router.HandleFunc("/something", handler).Methods(http.MethodGet) + + w := NewRecorder() + req := newRequest(http.MethodPut, "/thing") + + router.ServeHTTP(w, req) + + if w.Code != http.StatusNotFound { + t.Fatalf("Expected status code 404 (got %d)", w.Code) + } +} + type customMethodNotAllowedHandler struct { msg string }