Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Middleware Stack test #64

Merged
merged 4 commits into from
Aug 4, 2016
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions mux.go
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,9 @@ func (mx *Mux) ServeHTTP(w http.ResponseWriter, r *http.Request) {
// change the course of the request execution, or set request-scoped values for
// the next http.Handler.
func (mx *Mux) Use(middlewares ...func(http.Handler) http.Handler) {
if mx.handler != nil {
panic("chi: all middlewares must be defined before routes on a mux")
}
mx.middlewares = append(mx.middlewares, middlewares...)
}

Expand Down Expand Up @@ -160,6 +163,10 @@ func (mx *Mux) NotFound(handlerFn http.HandlerFunc) {
// for a group of handlers along the same routing path that use an additional
// set of middlewares. See _examples/.
func (mx *Mux) Group(fn func(r Router)) Router {
if mx.inline {
panic("chi: nested Group()'s are currently not supported")
}

// Similarly as in handle(), we must build the mux handler once further
// middleware registration isn't allowed for this stack, like now.
if !mx.inline && mx.handler == nil {
Expand Down Expand Up @@ -189,7 +196,17 @@ func (mx *Mux) Route(pattern string, fn func(r Router)) Router {
// Mount attaches another http.Handler or chi Router as a subrouter along a routing
// path. It's very useful to split up a large API as many independent routers and
// compose them as a single service using Mount. See _examples/.
//
// Note that Mount() simply sets a wildcard along the `pattern` that will continue
// routing at the `handler`, which in most cases is another chi.Router. As a result,
// if you define two Mount() routes on the exact same pattern the mount will panic.
func (mx *Mux) Mount(pattern string, handler http.Handler) {
// Provide runtime safety for ensuring a pattern isn't mounted on an existing
// routing pattern.
if mx.tree.findPattern(pattern+"*") != nil || mx.tree.findPattern(pattern+"/*") != nil {
panic(fmt.Sprintf("chi: attempting to Mount() a handler on an existing path, '%s'", pattern))
}

// Assign sub-Router's with the parent not found handler if not specified.
sr, ok := handler.(*Mux)
if ok && sr.notFoundHandler == nil && mx.notFoundHandler != nil {
Expand Down
37 changes: 37 additions & 0 deletions mux_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -830,6 +830,43 @@ func TestSingleHandler(t *testing.T) {
// r.Mount("/", r2)
// }

func TestMiddlewarePanicOnLateUse(t *testing.T) {
handler := func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("hello\n"))
}

mw := func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
next.ServeHTTP(w, r)
})
}

defer func() {
if recover() == nil {
t.Error("expected panic()")
}
}()

r := NewRouter()
r.Get("/", handler)
r.Use(mw) // Too late to apply middleware, we're expecting panic().
}

func TestMountingExistingPath(t *testing.T) {
handler := func(w http.ResponseWriter, r *http.Request) {}

defer func() {
if recover() == nil {
t.Error("expected panic()")
}
}()

r := NewRouter()
r.Get("/", handler)
r.Mount("/hi", http.HandlerFunc(handler))
r.Mount("/hi", http.HandlerFunc(handler))
}

func TestMuxFileServer(t *testing.T) {
fixtures := map[string]http.File{
"index.html": &testFile{"index.html", []byte("index\n")},
Expand Down
20 changes: 14 additions & 6 deletions tree.go
Original file line number Diff line number Diff line change
Expand Up @@ -168,15 +168,23 @@ func (n *node) InsertRoute(method methodTyp, pattern string, handler http.Handle
}

func (n *node) findPattern(pattern string) *node {
for {
if len(pattern) == 0 {
return n
nn := n
for _, nds := range nn.children {
if len(nds) == 0 {
continue
}
n = n.getEdge(pattern[0])

n = nn.getEdge(pattern[0])
if n == nil {
return nil // nothing
continue
}
pattern = pattern[len(n.prefix):]

xpattern := pattern[n.longestPrefix(pattern, n.prefix):]
if len(xpattern) == 0 {
return n
}

return n.findPattern(xpattern)
}
return nil
}
Expand Down