fix(tree): prefer a matching wildcard over a trailing-slash redirect [#4844]

With `/b/` and `/:name` registered, GET `/b` returned 404, or a 301 to `/b/`
when RedirectTrailingSlash is on, instead of being served by `/:name`. The
mirror shape does the same: with `/a/b` and `/:p/b/`, GET `/a/b/` is a 404.

getValue walks static children before wildcards and pushes the wildcard it
passed onto the skipped-nodes stack so it can roll back when the static branch
dead-ends. Two of those dead-ends never rolled back. When the unconsumed path
was exactly "/" the rollback loop was guarded off entirely, and when the static
branch produced a trailing-slash recommendation the rollback was skipped
because value.tsr was set. A recommendation to redirect is weaker than a route
that matches the request as it was sent, so it should not end the search.

Both sites now roll back, keeping the recommendation as the fallback for when
the wildcard branch finds nothing either. The remaining value.tsr assignments
only ever raise the flag now, so a recommendation recorded before a rollback
survives it; they were all reached with value.tsr already false before, so this
does not change their behaviour on its own.

Verified against a differential sweep of every 2- and 3-route combination of 21
route patterns in both insertion orders, 3080 route sets and 57592 lookups: no
request that previously matched a route matches a different one or stops
matching, and no trailing-slash recommendation is gained or lost.
This commit is contained in:
Ethan Stoner 2026-09-22 09:34:43 -07:00
parent 3b08cd7235
commit c28506934c
2 changed files with 81 additions and 25 deletions

64
tree.go
View File

@ -462,28 +462,32 @@ walk: // Outer loop for walking the tree
}
if !n.wildChild {
// If the path at the end of the loop is not equal to '/' and the current node has no child nodes
// the current node needs to roll back to last valid skippedNode
if path != "/" {
for length := len(*skippedNodes); length > 0; length-- {
skippedNode := (*skippedNodes)[length-1]
*skippedNodes = (*skippedNodes)[:length-1]
if strings.HasSuffix(skippedNode.path, path) {
path = skippedNode.path
n = skippedNode.node
if value.params != nil {
*value.params = (*value.params)[:skippedNode.paramsCount]
}
globalParamsCount = skippedNode.paramsCount
continue walk
// Nothing found below this node.
// We can recommend to redirect to the same URL without a
// trailing slash if a leaf exists for that path. That is only
// a recommendation though, so remember it and keep looking: a
// skipped wildcard that matches the request as it was sent
// beats redirecting the client somewhere else.
if path == "/" && n.handlers != nil {
value.tsr = true
}
// The current node needs to roll back to last valid skippedNode
for length := len(*skippedNodes); length > 0; length-- {
skippedNode := (*skippedNodes)[length-1]
*skippedNodes = (*skippedNodes)[:length-1]
if strings.HasSuffix(skippedNode.path, path) {
path = skippedNode.path
n = skippedNode.node
if value.params != nil {
*value.params = (*value.params)[:skippedNode.paramsCount]
}
globalParamsCount = skippedNode.paramsCount
continue walk
}
}
// Nothing found.
// We can recommend to redirect to the same URL without a
// trailing slash if a leaf exists for that path.
value.tsr = path == "/" && n.handlers != nil
return value
}
@ -538,7 +542,9 @@ walk: // Outer loop for walking the tree
}
// ... but we can't
value.tsr = len(path) == end+1
if len(path) == end+1 {
value.tsr = true
}
return value
}
@ -550,7 +556,9 @@ walk: // Outer loop for walking the tree
// No handle found. Check if a handle for this path + a
// trailing slash exists for TSR recommendation
n = n.children[0]
value.tsr = (n.path == "/" && n.handlers != nil) || (n.path == "" && n.indices == "/")
if (n.path == "/" && n.handlers != nil) || (n.path == "" && n.indices == "/") {
value.tsr = true
}
}
return value
@ -636,8 +644,10 @@ walk: // Outer loop for walking the tree
for i, c := range []byte(n.indices) {
if c == '/' {
n = n.children[i]
value.tsr = (len(n.path) == 1 && n.handlers != nil) ||
(n.nType == catchAll && n.children[0].handlers != nil)
if (len(n.path) == 1 && n.handlers != nil) ||
(n.nType == catchAll && n.children[0].handlers != nil) {
value.tsr = true
}
return value
}
}
@ -646,13 +656,17 @@ walk: // Outer loop for walking the tree
}
// Nothing found. We can recommend to redirect to the same URL with an
// extra trailing slash if a leaf exists for that path
value.tsr = path == "/" ||
// extra trailing slash if a leaf exists for that path. As above this is
// only a recommendation, so it does not stop the rollback below from
// looking for a route that matches the request as it was sent.
if path == "/" ||
(len(prefix) == len(path)+1 && prefix[len(path)] == '/' &&
path == prefix[:len(prefix)-1] && n.handlers != nil)
path == prefix[:len(prefix)-1] && n.handlers != nil) {
value.tsr = true
}
// roll back to last valid skippedNode
if !value.tsr && path != "/" {
if path != "/" {
for length := len(*skippedNodes); length > 0; length-- {
skippedNode := (*skippedNodes)[length-1]
*skippedNodes = (*skippedNodes)[:length-1]

View File

@ -673,6 +673,48 @@ func TestTreeTrailingSlashRedirect(t *testing.T) {
}
}
func TestTreeWildcardBeatsTrailingSlashRedirect(t *testing.T) {
// A route that matches the request as it was sent must win over a static
// route that differs from it only by a trailing slash, since the latter is
// no more than a redirect recommendation.
tree := &node{}
for _, route := range [...]string{"/b/", "/:name"} {
tree.addRoute(route, fakeHandler(route))
}
checkRequests(t, tree, testRequests{
{"/b", false, "/:name", Params{Param{Key: "name", Value: "b"}}},
{"/c", false, "/:name", Params{Param{Key: "name", Value: "c"}}},
{"/b/", false, "/b/", nil},
})
// The mirror shape, with the trailing slash on the wildcard route.
tree = &node{}
for _, route := range [...]string{"/a/b", "/:p/b/"} {
tree.addRoute(route, fakeHandler(route))
}
checkRequests(t, tree, testRequests{
{"/a/b/", false, "/:p/b/", Params{Param{Key: "p", Value: "a"}}},
{"/x/b/", false, "/:p/b/", Params{Param{Key: "p", Value: "x"}}},
{"/a/b", false, "/a/b", nil},
})
// Backtracking must not swallow the recommendation when no wildcard route
// can serve the request either.
tree = &node{}
for _, route := range [...]string{"/b/", "/:name/x"} {
tree.addRoute(route, fakeHandler(route))
}
value := tree.getValue("/b", nil, getSkippedNodes(), false)
if value.handlers != nil {
t.Fatalf("non-nil handler for TSR route '/b'")
} else if !value.tsr {
t.Errorf("expected TSR recommendation for route '/b'")
}
}
func TestTreeRootTrailingSlashRedirect(t *testing.T) {
tree := &node{}