Browse Source

Add a flag to require explicit method not allowed handler

pull/555/head
Tuan Nguyen 6 years ago
parent
commit
1ddce43e97
  1. 5
      mux.go
  2. 17
      mux_test.go

5
mux.go

@ -51,6 +51,9 @@ type Router struct { @@ -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) { @@ -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()
}

17
mux_test.go

@ -2733,6 +2733,23 @@ func TestMethodNotAllowed(t *testing.T) { @@ -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
}

Loading…
Cancel
Save