Skip to content

Commit dde8a3e

Browse files
committed
Fixes path order dependent response when a nil handler is defined for a route(gorilla#515)
1 parent e1863a6 commit dde8a3e

File tree

2 files changed

+46
-2
lines changed

2 files changed

+46
-2
lines changed

mux_test.go

+42
Original file line numberDiff line numberDiff line change
@@ -2803,6 +2803,48 @@ func TestSubrouterNotFound(t *testing.T) {
28032803
}
28042804
}
28052805

2806+
// testOptionsMiddleWare returns 200 on an OPTIONS request
2807+
func testOptionsMiddleWare(inner http.Handler) http.Handler {
2808+
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
2809+
if r.Method == http.MethodOptions {
2810+
w.WriteHeader(http.StatusOK)
2811+
return
2812+
}
2813+
inner.ServeHTTP(w, r)
2814+
})
2815+
}
2816+
2817+
// TestRouterOrder Should Pass whichever order route is defined
2818+
func TestRouterOrder(t *testing.T) {
2819+
handler := func(w http.ResponseWriter, r *http.Request) {}
2820+
router := NewRouter()
2821+
router.Path("/a/b").Handler(http.HandlerFunc(handler)).Methods(http.MethodGet)
2822+
router.Path("/a/{a}").Handler(nil).Methods(http.MethodOptions)
2823+
router.Use(MiddlewareFunc(testOptionsMiddleWare))
2824+
2825+
w := NewRecorder()
2826+
req := newRequest(http.MethodOptions, "/a/b")
2827+
2828+
router.ServeHTTP(w, req)
2829+
2830+
if w.Code != http.StatusOK {
2831+
t.Fatalf("Expected status code 200 (got %d)", w.Code)
2832+
}
2833+
2834+
reversedPathRouter := NewRouter()
2835+
reversedPathRouter.Path("/a/{a}").Handler(http.HandlerFunc(handler)).Methods(http.MethodGet)
2836+
reversedPathRouter.Path("/a/b").Handler(nil).Methods(http.MethodOptions)
2837+
reversedPathRouter.Use(MiddlewareFunc(testOptionsMiddleWare))
2838+
2839+
w = NewRecorder()
2840+
2841+
reversedPathRouter.ServeHTTP(w, req)
2842+
2843+
if w.Code != http.StatusOK {
2844+
t.Fatalf("Expected status code 200 (got %d)", w.Code)
2845+
}
2846+
}
2847+
28062848
// mapToPairs converts a string map to a slice of string pairs
28072849
func mapToPairs(m map[string]string) []string {
28082850
var i int

route.go

+4-2
Original file line numberDiff line numberDiff line change
@@ -74,11 +74,13 @@ func (r *Route) Match(req *http.Request, match *RouteMatch) bool {
7474
return false
7575
}
7676

77-
if match.MatchErr == ErrMethodMismatch && r.handler != nil {
77+
if match.MatchErr == ErrMethodMismatch {
7878
// We found a route which matches request method, clear MatchErr
7979
match.MatchErr = nil
8080
// Then override the mis-matched handler
81-
match.Handler = r.handler
81+
if r.handler != nil {
82+
match.Handler = r.handler
83+
}
8284
}
8385

8486
// Yay, we have a match. Let's collect some info about it.

0 commit comments

Comments
 (0)