Skip to content

Commit

Permalink
Fix Route function to avoid middleware duplication (#22)
Browse files Browse the repository at this point in the history
  • Loading branch information
vearutop authored Jan 30, 2021
1 parent b7e7c07 commit 086dcc9
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 13 deletions.
2 changes: 1 addition & 1 deletion chirouter/wrapper.go
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ func (r *Wrapper) Route(pattern string, fn func(r chi.Router)) chi.Router {
fn(subRouter)
}

r.Mount(pattern, subRouter)
r.Router.Mount(pattern, subRouter)

return subRouter
}
Expand Down
29 changes: 17 additions & 12 deletions chirouter/wrapper_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,14 +42,15 @@ func TestNewWrapper(t *testing.T) {
return http.HandlerFunc(handler.ServeHTTP)
})

r.Use(func(handler http.Handler) http.Handler {
var foo interface{ Foo() }
if nethttp.HandlerAs(handler, &foo) {
return HandlerWithBar{Handler: handler}
}
mw := func(handler http.Handler) http.Handler {
var bar interface{ Bar() }

return handler
})
assert.False(t, nethttp.HandlerAs(handler, &bar))

return HandlerWithBar{Handler: handler}
}

r.Use(mw)

r.Group(func(r chi.Router) {
r.Method(http.MethodPost,
Expand All @@ -62,6 +63,8 @@ func TestNewWrapper(t *testing.T) {
)
})

r.Mount("/mount", http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {}))

r.Route("/deeper/", func(r chi.Router) {
r.Use(func(handler http.Handler) http.Handler {
return handler
Expand All @@ -82,11 +85,13 @@ func TestNewWrapper(t *testing.T) {
r.Handle("/bar", http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {}))
})

req, err := http.NewRequest(http.MethodPost, "/baz/123/", nil)
require.NoError(t, err)
for _, u := range []string{"/baz/123/", "/deeper/foo", "/mount/abc"} {
req, err := http.NewRequest(http.MethodPost, u, nil)
require.NoError(t, err)

rw := httptest.NewRecorder()
r.ServeHTTP(rw, req)
rw := httptest.NewRecorder()
r.ServeHTTP(rw, req)

assert.Equal(t, "bar", rw.Body.String())
assert.Equal(t, "bar", rw.Body.String(), u)
}
}
2 changes: 2 additions & 0 deletions nethttp/wrap.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ func WrapHandler(h http.Handler, mw ...func(http.Handler) http.Handler) http.Han
h = &wrappedHandler{
Handler: w,
wrapped: h,
mwName: runtime.FuncForPC(reflect.ValueOf(mw[i]).Pointer()).Name(),
}
}

Expand Down Expand Up @@ -81,4 +82,5 @@ var handlerType = reflect.TypeOf((*http.Handler)(nil)).Elem()
type wrappedHandler struct {
http.Handler
wrapped http.Handler
mwName string
}

0 comments on commit 086dcc9

Please sign in to comment.