Merge 1513c3266a6adddfc893099e2a3d2ead2b170ba6 into 1bd0ecf2d3e08da37efa270bb7be20c1eddb0d68

This commit is contained in:
Jeremy Schoemaker 2026-09-25 01:30:42 -05:00 committed by GitHub
commit dc8554a2f1
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 32 additions and 0 deletions

View File

@ -941,3 +941,26 @@ func TestIssue4818_MethodNotAllowedManyTrees(t *testing.T) {
t.Fatalf("expected 405, got %d", w.Code)
}
}
// TestRouterSkippedNodesGrowsAfterLateRouteRegistration ensures that a Context
// recycled from the pool can still walk a tree that became deeper after the
// Context was allocated. The skippedNodes stack is sized from engine.maxSections
// at allocation time, so routes registered after the first request used to make
// the tree walk reslice the stack beyond its capacity and panic.
func TestRouterSkippedNodesGrowsAfterLateRouteRegistration(t *testing.T) {
router := New()
router.GET("/a", func(c *Context) { c.String(http.StatusOK, "a") })
// Seed the pool with a Context sized for the shallow tree.
w := PerformRequest(router, http.MethodGet, "/a")
assert.Equal(t, http.StatusOK, w.Code)
// Deepen the tree after a Context has already been pooled.
router.GET("/x/:p", func(c *Context) { c.String(http.StatusOK, "p") })
router.GET("/x/y/:q", func(c *Context) { c.String(http.StatusOK, "q") })
router.GET("/x/y/z/w", func(c *Context) { c.String(http.StatusOK, "w") })
w = PerformRequest(router, http.MethodGet, "/x/y/z/w")
assert.Equal(t, http.StatusOK, w.Code)
assert.Equal(t, "w", w.Body.String())
}

View File

@ -440,6 +440,15 @@ walk: // Outer loop for walking the tree
// strings.HasPrefix(n.children[len(n.children)-1].path, ":") == n.wildChild
if n.wildChild {
index := len(*skippedNodes)
// Preallocate capacity if necessary: the stack is
// sized from engine.maxSections when the Context was
// allocated, which can be stale for a pooled Context
// if routes were registered later.
if cap(*skippedNodes) < index+1 {
newSkippedNodes := make([]skippedNode, len(*skippedNodes), index+1)
copy(newSkippedNodes, *skippedNodes)
*skippedNodes = newSkippedNodes
}
*skippedNodes = (*skippedNodes)[:index+1]
(*skippedNodes)[index] = skippedNode{
path: prefix + path,