Skip to content

Commit

Permalink
Fixes the CORSMethodMiddleware bug with SubRouters
Browse files Browse the repository at this point in the history
* Adds a test case for the repro given in issue #534
* Fixes the logic in CORSMethodMiddleware to handle matching routes
better
  • Loading branch information
fharding1 committed Nov 14, 2019
1 parent ff4e71f commit 8b29de0
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 15 deletions.
25 changes: 10 additions & 15 deletions middleware.go
Original file line number Diff line number Diff line change
Expand Up @@ -58,22 +58,17 @@ func CORSMethodMiddleware(r *Router) MiddlewareFunc {
func getAllMethodsForRoute(r *Router, req *http.Request) ([]string, error) {
var allMethods []string

err := r.Walk(func(route *Route, _ *Router, _ []*Route) error {
for _, m := range route.matchers {
if _, ok := m.(*routeRegexp); ok {
if m.Match(req, &RouteMatch{}) {
methods, err := route.GetMethods()
if err != nil {
return err
}

allMethods = append(allMethods, methods...)
}
break
for _, route := range r.routes {
match := RouteMatch{}
if route.Match(req, &match) || match.MatchErr == ErrMethodMismatch {
methods, err := route.GetMethods()
if err != nil {
return nil, err
}

allMethods = append(allMethods, methods...)
}
return nil
})
}

return allMethods, err
return allMethods, nil
}
20 changes: 20 additions & 0 deletions middleware_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -478,6 +478,26 @@ func TestCORSMethodMiddleware(t *testing.T) {
}
}

func TestCORSMethodMiddlewareSubrouter(t *testing.T) {
router := NewRouter().StrictSlash(true)

subrouter := router.PathPrefix("/test").Subrouter()
subrouter.HandleFunc("/hello", stringHandler("a")).Methods(http.MethodGet, http.MethodOptions, http.MethodPost)
subrouter.HandleFunc("/hello/{name}", stringHandler("b")).Methods(http.MethodGet, http.MethodOptions)

subrouter.Use(CORSMethodMiddleware(subrouter))

rw := NewRecorder()
req := newRequest("GET", "/test/hello/asdf")
router.ServeHTTP(rw, req)

actualMethods := rw.Header().Get("Access-Control-Allow-Methods")
expectedMethods := "GET,OPTIONS"
if actualMethods != expectedMethods {
t.Fatalf("expected methods %q but got: %q", expectedMethods, actualMethods)
}
}

func TestMiddlewareOnMultiSubrouter(t *testing.T) {
first := "first"
second := "second"
Expand Down

0 comments on commit 8b29de0

Please sign in to comment.