Browse Source

Update ancestors parameter for WalkFunc for matcher subrouters

Fixes #263
pull/268/head
Nick Miyake 9 years ago committed by Kamil Kisiel
parent
commit
4d814f7650
  1. 2
      mux.go
  2. 25
      mux_test.go

2
mux.go

@ -308,10 +308,12 @@ func (r *Router) walk(walkFn WalkFunc, ancestors []*Route) error {
} }
for _, sr := range t.matchers { for _, sr := range t.matchers {
if h, ok := sr.(*Router); ok { if h, ok := sr.(*Router); ok {
ancestors = append(ancestors, t)
err := h.walk(walkFn, ancestors) err := h.walk(walkFn, ancestors)
if err != nil { if err != nil {
return err return err
} }
ancestors = ancestors[:len(ancestors)-1]
} }
} }
if h, ok := t.handler.(*Router); ok { if h, ok := t.handler.(*Router); ok {

25
mux_test.go

@ -11,6 +11,7 @@ import (
"fmt" "fmt"
"net/http" "net/http"
"net/url" "net/url"
"reflect"
"strings" "strings"
"testing" "testing"
) )
@ -1382,22 +1383,38 @@ func TestWalkNested(t *testing.T) {
l2 := l1.PathPrefix("/l").Subrouter() l2 := l1.PathPrefix("/l").Subrouter()
l2.Path("/a") 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 idx := 0
err := router.Walk(func(route *Route, router *Router, ancestors []*Route) error { err := router.Walk(func(route *Route, router *Router, ancestors []*Route) error {
path := paths[idx] path := testCases[idx].path
tpl := route.regexp.path.template tpl := route.regexp.path.template
if tpl != path { if tpl != path {
t.Errorf(`Expected %s got %s`, path, tpl) 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++ idx++
return nil return nil
}) })
if err != nil { if err != nil {
panic(err) panic(err)
} }
if idx != len(paths) { if idx != len(testCases) {
t.Errorf("Expected %d routes, found %d", len(paths), idx) t.Errorf("Expected %d routes, found %d", len(testCases), idx)
} }
} }

Loading…
Cancel
Save