Skip to content

Commit

Permalink
Update ancestors parameter for WalkFunc for matcher subrouters
Browse files Browse the repository at this point in the history
  • Loading branch information
nmiyake authored and kisielk committed May 22, 2017
1 parent a322b2c commit 4d814f7
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 4 deletions.
2 changes: 2 additions & 0 deletions mux.go
Original file line number Diff line number Diff line change
Expand Up @@ -308,10 308,12 @@ func (r *Router) walk(walkFn WalkFunc, ancestors []*Route) error {
}
for _, sr := range t.matchers {
if h, ok := sr.(*Router); ok {
ancestors = append(ancestors, t)
err := h.walk(walkFn, ancestors)
if err != nil {
return err
}
ancestors = ancestors[:len(ancestors)-1]
}
}
if h, ok := t.handler.(*Router); ok {
Expand Down
25 changes: 21 additions & 4 deletions mux_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 11,7 @@ import (
"fmt"
"net/http"
"net/url"
"reflect"
"strings"
"testing"
)
Expand Down Expand Up @@ -1382,22 1383,38 @@ func TestWalkNested(t *testing.T) {
l2 := l1.PathPrefix("/l").Subrouter()
l2.Path("/a")

paths := []string{"/g", "/g/o", "/g/o/r", "/g/o/r/i", "/g/o/r/i/l", "/g/o/r/i/l/l", "/g/o/r/i/l/l/a"}
testCases := []struct {
path string
ancestors []*Route
}{
{"/g", []*Route{}},
{"/g/o", []*Route{g.parent.(*Route)}},
{"/g/o/r", []*Route{g.parent.(*Route), o.parent.(*Route)}},
{"/g/o/r/i", []*Route{g.parent.(*Route), o.parent.(*Route), r.parent.(*Route)}},
{"/g/o/r/i/l", []*Route{g.parent.(*Route), o.parent.(*Route), r.parent.(*Route), i.parent.(*Route)}},
{"/g/o/r/i/l/l", []*Route{g.parent.(*Route), o.parent.(*Route), r.parent.(*Route), i.parent.(*Route), l1.parent.(*Route)}},
{"/g/o/r/i/l/l/a", []*Route{g.parent.(*Route), o.parent.(*Route), r.parent.(*Route), i.parent.(*Route), l1.parent.(*Route), l2.parent.(*Route)}},
}

idx := 0
err := router.Walk(func(route *Route, router *Router, ancestors []*Route) error {
path := paths[idx]
path := testCases[idx].path
tpl := route.regexp.path.template
if tpl != path {
t.Errorf(`Expected %s got %s`, path, tpl)
}
currWantAncestors := testCases[idx].ancestors
if !reflect.DeepEqual(currWantAncestors, ancestors) {
t.Errorf(`Expected % v got % v`, currWantAncestors, ancestors)
}
idx
return nil
})
if err != nil {
panic(err)
}
if idx != len(paths) {
t.Errorf("Expected %d routes, found %d", len(paths), idx)
if idx != len(testCases) {
t.Errorf("Expected %d routes, found %d", len(testCases), idx)
}
}

Expand Down

0 comments on commit 4d814f7

Please sign in to comment.