Skip to content

Commit 8c27828

Browse files
authored
Merge pull request #1659 from pafuent/panic_router_find_fails_on_params_with_no_root
Fixed panic when Router#Find fails on Param paths
2 parents 6caec30 + c171855 commit 8c27828

File tree

2 files changed

+37
-1
lines changed

2 files changed

+37
-1
lines changed

router.go

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -428,7 +428,9 @@ func (r *Router) Find(method, path string, c Context) {
428428
pos := strings.IndexByte(ns, '/')
429429
if pos == -1 {
430430
// If no slash is remaining in search string set param value
431-
pvalues[len(cn.pnames)-1] = search
431+
if len(cn.pnames) > 0 {
432+
pvalues[len(cn.pnames)-1] = search
433+
}
432434
break
433435
} else if pos > 0 {
434436
// Otherwise continue route processing with restored next node

router_test.go

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1298,6 +1298,40 @@ func TestRouterParam1466(t *testing.T) {
12981298
assert.Equal(t, 0, c.response.Status)
12991299
}
13001300

1301+
// Issue #1653
1302+
func TestRouterPanicWhenParamNoRootOnlyChildsFailsFind(t *testing.T) {
1303+
e := New()
1304+
r := e.router
1305+
1306+
r.Add(http.MethodGet, "/users/create", handlerHelper("create", 1))
1307+
r.Add(http.MethodGet, "/users/:id/edit", func(c Context) error {
1308+
return nil
1309+
})
1310+
r.Add(http.MethodGet, "/users/:id/active", func(c Context) error {
1311+
return nil
1312+
})
1313+
1314+
c := e.NewContext(nil, nil).(*context)
1315+
r.Find(http.MethodGet, "/users/alice/edit", c)
1316+
assert.Equal(t, "alice", c.Param("id"))
1317+
1318+
c = e.NewContext(nil, nil).(*context)
1319+
r.Find(http.MethodGet, "/users/bob/active", c)
1320+
assert.Equal(t, "bob", c.Param("id"))
1321+
1322+
c = e.NewContext(nil, nil).(*context)
1323+
r.Find(http.MethodGet, "/users/create", c)
1324+
c.Handler()(c)
1325+
assert.Equal(t, 1, c.Get("create"))
1326+
assert.Equal(t, "/users/create", c.Get("path"))
1327+
1328+
//This panic before the fix for Issue #1653
1329+
c = e.NewContext(nil, nil).(*context)
1330+
r.Find(http.MethodGet, "/users/createNotFound", c)
1331+
he := c.Handler()(c).(*HTTPError)
1332+
assert.Equal(t, http.StatusNotFound, he.Code)
1333+
}
1334+
13011335
func benchmarkRouterRoutes(b *testing.B, routes []*Route) {
13021336
e := New()
13031337
r := e.router

0 commit comments

Comments
 (0)