Browse Source

Merge pull request #535 from fharding1/cors-subrouter-bug

Fix the CORSMethodMiddleware bug with subrouters
pull/536/head
Matt Silverlock 6 years ago committed by GitHub
parent
commit
2854a05fd3
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
  1. 25
      middleware.go
  2. 20
      middleware_test.go

25
middleware.go

@ -58,22 +58,17 @@ func CORSMethodMiddleware(r *Router) MiddlewareFunc { @@ -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 {
var 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
middleware_test.go

@ -478,6 +478,26 @@ func TestCORSMethodMiddleware(t *testing.T) { @@ -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"

Loading…
Cancel
Save