Skip to content

Commit

Permalink
Call mux.NewRouter() in pat.New() (#31)
Browse files Browse the repository at this point in the history
Initializing mux.Router with a zero value breaks route naming: the
`mux.Router.namedRoutes` map remains nil and an attempt to assign a
route name panics.

This fix simply delegates mux.Router creation to its constructor, which
does the right thing.
  • Loading branch information
rtfb committed Dec 7, 2023
1 parent 2ef8c2c commit b1685f4
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 1 deletion.
4 changes: 3 additions & 1 deletion pat.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,9 @@ import (

// New returns a new router.
func New() *Router {
return &Router{}
return &Router{
Router: *mux.NewRouter(),
}
}

// Router is a request router that implements a pat-like API.
Expand Down
18 changes: 18 additions & 0 deletions pat_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -62,3 +62,21 @@ func TestPatMatch(t *testing.T) {
testMatch(t, "GET", "/foo/x{name}", "/foo/xbar/baz", true, map[string]string{":name": "bar"})
testMatch(t, "PATCH", "/foo/x{name}", "/foo/xbar/baz", true, map[string]string{":name": "bar"})
}

func TestNamedRoutes(t *testing.T) {
router := New()
route := router.Get("/", nil)
name := "foo"
route.Name(name)
if route.GetError() != nil {
t.Errorf("Route name assign: %v", route.GetError())
}
gotRoute := router.Router.Get(name)
if gotRoute == nil {
t.Errorf("mux.Router.Get by name returned nil")
}
gotName := gotRoute.GetName()
if gotName != name {
t.Errorf("Unexpected route name: got=%q, want=%q", gotName, name)
}
}

0 comments on commit b1685f4

Please sign in to comment.