Skip to content

Commit

Permalink
bugfix/subrouter custom methodNotAllowed handler returning 404 (#509)
Browse files Browse the repository at this point in the history
  • Loading branch information
jonas committed Aug 20, 2019
1 parent e67b3c0 commit db220ca
Show file tree
Hide file tree
Showing 2 changed files with 59 additions and 1 deletion.
58 changes: 58 additions & 0 deletions mux_test.go
Original file line number Diff line number Diff line change
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
Original file line number Diff line number Diff line change
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

0 comments on commit db220ca

Please sign in to comment.