Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

bugfix/subrouter custom methodNotAllowed handler returning 404 (#509) #510

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
58 changes: 58 additions & 0 deletions mux_test.go
Expand Up @@ -9,6 +9,7 @@ import (
"bytes"
"errors"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"reflect"
Expand Down Expand Up @@ -2729,6 +2730,63 @@ func TestMethodNotAllowed(t *testing.T) {
}
}

type customMethodNotAllowedHandler struct {
msg string
}

func (h customMethodNotAllowedHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusMethodNotAllowed)
fmt.Fprint(w, h.msg)
}

func TestSubrouterCustomMethodNotAllowed(t *testing.T) {
handler := func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) }

router := NewRouter()
router.HandleFunc("/test", handler).Methods(http.MethodGet)
router.MethodNotAllowedHandler = customMethodNotAllowedHandler{msg: "custom router handler"}

subrouter := router.PathPrefix("/sub").Subrouter()
subrouter.HandleFunc("/test", handler).Methods(http.MethodGet)
subrouter.MethodNotAllowedHandler = customMethodNotAllowedHandler{msg: "custom sub router handler"}

testCases := map[string]struct {
path string
expMsg string
}{
"router method not allowed": {
path: "/test",
expMsg: "custom router handler",
},
"subrouter method not allowed": {
path: "/sub/test",
expMsg: "custom sub router handler",
},
}

for name, tc := range testCases {
t.Run(name, func(tt *testing.T) {
w := NewRecorder()
req := newRequest(http.MethodPut, tc.path)

router.ServeHTTP(w, req)

if w.Code != http.StatusMethodNotAllowed {
tt.Errorf("Expected status code 405 (got %d)", w.Code)
}

b, err := ioutil.ReadAll(w.Body)
if err != nil {
tt.Errorf("failed to read body: %v", err)
}

if string(b) != tc.expMsg {
tt.Errorf("expected msg %q, got %q", tc.expMsg, string(b))
}
})
}
}

func TestSubrouterNotFound(t *testing.T) {
handler := func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) }
router := NewRouter()
Expand Down
2 changes: 1 addition & 1 deletion route.go
Expand Up @@ -74,7 +74,7 @@ func (r *Route) Match(req *http.Request, match *RouteMatch) bool {
return false
}

if match.MatchErr == ErrMethodMismatch {
if match.MatchErr == ErrMethodMismatch && r.handler != nil {
// We found a route which matches request method, clear MatchErr
match.MatchErr = nil
// Then override the mis-matched handler
Expand Down