mirror of
https://github.com/gin-gonic/gin.git
synced 2026-11-23 11:33:37 +08:00
Merge 1513c3266a6adddfc893099e2a3d2ead2b170ba6 into 1bd0ecf2d3e08da37efa270bb7be20c1eddb0d68
This commit is contained in:
commit
dc8554a2f1
@ -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())
|
||||
}
|
||||
|
||||
9
tree.go
9
tree.go
@ -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,
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user