fix: correct shallow copy in router backtracking

The router could panic with a 'slice bounds out of range' error when handling requests that trigger its backtracking logic.

The root cause was a shallow copy of the node's `children` slice when creating a `skippedNode` for backtracking. This could lead to a corrupted state if the router needed to backtrack and then proceed down a wildcard path.

This commit fixes the issue by introducing a `copyChildren` method on the `node` struct, which creates a safe copy of the children slice. This method is now used when creating a `skippedNode`, ensuring that the backtracking logic is isolated and robust.
This commit is contained in:
google-labs-jules[bot] 2025-08-01 00:49:53 +00:00
parent 1e7682ad84
commit e43b12e343

View file

@ -293,6 +293,12 @@ walk: // 外部循环用于遍历和构建路由树
}
}
func (n *node) copyChildren() []*node {
children := make([]*node, len(n.children))
copy(children, n.children)
return children
}
// findWildcard 搜索通配符段并检查名称是否包含无效字符。
// 如果未找到通配符,则返回 -1 作为索引。
func findWildcard(path string) (wildcard string, i int, valid bool) {
@ -486,7 +492,7 @@ walk: // 外部循环用于遍历路由树
wildChild: n.wildChild,
nType: n.nType,
priority: n.priority,
children: n.children,
children: n.copyChildren(),
handlers: n.handlers,
fullPath: n.fullPath,
},