diff --git a/mux_test.go b/mux_test.go index cb3bbe0a..5390ad8b 100644 --- a/mux_test.go +++ b/mux_test.go @@ -2095,8 +2095,8 @@ func TestMultipleDefinitionOfSamePathWithDifferentMethods(t *testing.T) { if matched { t.Error("Should not have matched route for methods") } - if match.MatchErr != ErrNotFound { - t.Error("Should have ErrNotFound error. Found:", match.MatchErr) + if match.MatchErr != ErrMethodMismatch { + t.Error("Should have ErrMethodMismatch error. Found:", match.MatchErr) } }) @@ -2114,6 +2114,30 @@ func TestMultipleDefinitionOfSamePathWithDifferentMethods(t *testing.T) { } }) + t.Run("A mismach method of a valid path on subrouter should return ErrMethodMismatch", func(t *testing.T) { + r := NewRouter() + r.MethodNotAllowedHandler = http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) { + rw.WriteHeader(http.StatusMethodNotAllowed) + _, _ = rw.Write([]byte("Method not allowed")) + }) + + subrouter := r.PathPrefix("/v1").Subrouter() + subrouter.HandleFunc("/api", func(w http.ResponseWriter, e *http.Request) { + _, _ = w.Write([]byte("Logic")) + }).Methods("GET") + subrouter.HandleFunc("/api/{id}", func(w http.ResponseWriter, e *http.Request) { + _, _ = w.Write([]byte("Logic")) + }).Methods("GET") + + rw := NewRecorder() + req, _ := http.NewRequest("POST", "/v1/api", nil) + r.ServeHTTP(rw, req) + + if rw.Code != http.StatusMethodNotAllowed { + t.Fatalf("Should have status code 405 (StatusMethodNotAllowed). Got %v\n", rw.Code) + } + }) + } func TestErrMatchNotFound(t *testing.T) { diff --git a/route.go b/route.go index 8a9e754a..0a68b1b6 100644 --- a/route.go +++ b/route.go @@ -66,16 +66,6 @@ func (r *Route) Match(req *http.Request, match *RouteMatch) bool { matchErr = nil // nolint:ineffassign return false - } else { - // Multiple routes may share the same path but use different HTTP methods. For instance: - // Route 1: POST "/users/{id}". - // Route 2: GET "/users/{id}", parameters: "id": "[0-9]+". - // - // The router must handle these cases correctly. For a GET request to "/users/abc" with "id" as "-2", - // The router should return a "Not Found" error as no route fully matches this request. - if match.MatchErr == ErrMethodMismatch { - match.MatchErr = nil - } } }