Merge a010002b100a0856ea3f06f7085dae608fb1cb06 into 0f09c3a9b4626d9fe9979cf4d0521d6ae32ab646

This commit is contained in:
adam magued 2026-11-01 15:58:21 +00:00 committed by GitHub
commit 7758b0c59d
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
3 changed files with 243 additions and 22 deletions

View File

@ -1195,3 +1195,109 @@ func TestRouterQueryMethod(t *testing.T) {
router.ServeHTTP(w2, req2)
assert.Equal(t, http.StatusNotFound, w2.Code)
}
func TestRouterParamRouteWithTrailingSlashSibling(t *testing.T) {
for _, redirectTrailingSlash := range []bool{false, true} {
// Case 1: Route /b/ and /:name, request /b
router1 := New()
router1.RedirectTrailingSlash = redirectTrailingSlash
var matchedRoute string
var matchedParams Params
router1.GET("/b/", func(c *Context) {
matchedRoute = "/b/"
matchedParams = c.Params
c.String(http.StatusOK, "b_slash")
})
router1.GET("/:name", func(c *Context) {
matchedRoute = "/:name"
matchedParams = c.Params
c.String(http.StatusOK, "name")
})
// GET /b -> should match /:name with name=b
w := httptest.NewRecorder()
req, _ := http.NewRequest(http.MethodGet, "/b", nil)
router1.ServeHTTP(w, req)
assert.Equal(t, http.StatusOK, w.Code)
assert.Equal(t, "/:name", matchedRoute)
assert.Equal(t, Params{Param{Key: "name", Value: "b"}}, matchedParams)
// GET /b/ -> should match /b/
w = httptest.NewRecorder()
req, _ = http.NewRequest(http.MethodGet, "/b/", nil)
router1.ServeHTTP(w, req)
assert.Equal(t, http.StatusOK, w.Code)
assert.Equal(t, "/b/", matchedRoute)
// GET /c -> should match /:name with name=c
w = httptest.NewRecorder()
req, _ = http.NewRequest(http.MethodGet, "/c", nil)
router1.ServeHTTP(w, req)
assert.Equal(t, http.StatusOK, w.Code)
assert.Equal(t, "/:name", matchedRoute)
assert.Equal(t, Params{Param{Key: "name", Value: "c"}}, matchedParams)
// Case 2: Mirror case: /a/b and /:p/b/, request /a/b/
router2 := New()
router2.RedirectTrailingSlash = redirectTrailingSlash
router2.GET("/a/b", func(c *Context) {
matchedRoute = "/a/b"
matchedParams = c.Params
c.String(http.StatusOK, "ab")
})
router2.GET("/:p/b/", func(c *Context) {
matchedRoute = "/:p/b/"
matchedParams = c.Params
c.String(http.StatusOK, "pb_slash")
})
// GET /a/b/ -> should match /:p/b/ with p=a
w = httptest.NewRecorder()
req, _ = http.NewRequest(http.MethodGet, "/a/b/", nil)
router2.ServeHTTP(w, req)
assert.Equal(t, http.StatusOK, w.Code)
assert.Equal(t, "/:p/b/", matchedRoute)
assert.Equal(t, Params{Param{Key: "p", Value: "a"}}, matchedParams)
// GET /a/b -> should match /a/b
w = httptest.NewRecorder()
req, _ = http.NewRequest(http.MethodGet, "/a/b", nil)
router2.ServeHTTP(w, req)
assert.Equal(t, http.StatusOK, w.Code)
assert.Equal(t, "/a/b", matchedRoute)
// Case 3: Wildcard sibling interaction: /:a/b/ and /:a/b, request /foo/b
router3 := New()
router3.RedirectTrailingSlash = redirectTrailingSlash
router3.GET("/:a/b/", func(c *Context) {
matchedRoute = "/:a/b/"
matchedParams = c.Params
c.String(http.StatusOK, "ab_slash")
})
router3.GET("/:a/b", func(c *Context) {
matchedRoute = "/:a/b"
matchedParams = c.Params
c.String(http.StatusOK, "ab")
})
// GET /foo/b -> should match /:a/b with a=foo
w = httptest.NewRecorder()
req, _ = http.NewRequest(http.MethodGet, "/foo/b", nil)
router3.ServeHTTP(w, req)
assert.Equal(t, http.StatusOK, w.Code)
assert.Equal(t, "/:a/b", matchedRoute)
assert.Equal(t, Params{Param{Key: "a", Value: "foo"}}, matchedParams)
// GET /foo/b/ -> should match /:a/b/ with a=foo
w = httptest.NewRecorder()
req, _ = http.NewRequest(http.MethodGet, "/foo/b/", nil)
router3.ServeHTTP(w, req)
assert.Equal(t, http.StatusOK, w.Code)
assert.Equal(t, "/:a/b/", matchedRoute)
assert.Equal(t, Params{Param{Key: "a", Value: "foo"}}, matchedParams)
}
}

52
tree.go
View File

@ -426,6 +426,7 @@ func (n *node) getValue(path string, params *Params, skippedNodes *[]skippedNode
// able to record one more backtrack frame. A raw reslice of the capacity
// captured at pool allocation panics with "slice bounds out of range".
*skippedNodes = (*skippedNodes)[:0]
value.tsr = false
walk: // Outer loop for walking the tree
for {
@ -461,28 +462,28 @@ 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
// If the current node has no child nodes,
// roll back to last valid skippedNode
cTsr := path == "/" && n.handlers != nil
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
value.tsr = value.tsr || cTsr
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
value.tsr = value.tsr || cTsr
return value
}
@ -537,20 +538,24 @@ walk: // Outer loop for walking the tree
}
// ... but we can't
value.tsr = len(path) == end+1
cTsr := len(path) == end+1
value.tsr = value.tsr || cTsr
return value
}
if value.handlers = n.handlers; value.handlers != nil {
value.fullPath = n.fullPath
value.tsr = false
return value
}
cTsr := false
if len(n.children) == 1 {
// 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 == "/")
cTsr = (n.path == "/" && n.handlers != nil) || (n.path == "" && n.indices == "/")
}
value.tsr = value.tsr || cTsr
return value
case catchAll:
@ -583,6 +588,7 @@ walk: // Outer loop for walking the tree
value.handlers = n.handlers
value.fullPath = n.fullPath
value.tsr = false
return value
default:
@ -592,7 +598,7 @@ walk: // Outer loop for walking the tree
}
if path == prefix {
// If the current path does not equal '/' and the node does not have a registered handle and the most recently matched node has a child node
// If the current node does not have a registered handle,
// the current node needs to roll back to last valid skippedNode
if n.handlers == nil && path != "/" {
for length := len(*skippedNodes); length > 0; length-- {
@ -608,12 +614,12 @@ walk: // Outer loop for walking the tree
continue walk
}
}
// n = latestNode.children[len(latestNode.children)-1]
}
// We should have reached the node containing the handle.
// Check if this node has a handle registered.
if value.handlers = n.handlers; value.handlers != nil {
value.fullPath = n.fullPath
value.tsr = false
return value
}
@ -636,7 +642,7 @@ walk: // Outer loop for walking the tree
if c == '/' {
n = n.children[i]
value.tsr = (len(n.path) == 1 && n.handlers != nil) ||
(n.nType == catchAll && n.children[0].handlers != nil)
(n.nType == catchAll && len(n.children) > 0 && n.children[0].handlers != nil)
return value
}
}
@ -646,12 +652,12 @@ 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 == "/" ||
cTsr := path == "/" ||
(len(prefix) == len(path)+1 && prefix[len(path)] == '/' &&
path == prefix[:len(prefix)-1] && n.handlers != nil)
// 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]
@ -662,11 +668,13 @@ walk: // Outer loop for walking the tree
*value.params = (*value.params)[:skippedNode.paramsCount]
}
globalParamsCount = skippedNode.paramsCount
value.tsr = value.tsr || cTsr
continue walk
}
}
}
value.tsr = value.tsr || cTsr
return value
}
}

View File

@ -1111,3 +1111,110 @@ func TestTreeFindCaseInsensitivePathWildcardParamAndStaticChild(t *testing.T) {
t.Errorf("Wrong result for '/prefix/something': %s", string(out))
}
}
func TestTreeTrailingSlashAndParamRoute(t *testing.T) {
// Case 1: Route /b/ and /:name, request /b
// GET /b should match /:name with param name="b", rather than redirecting to /b/
tree := &node{}
routes := []string{
"/b/",
"/:name",
}
for _, route := range routes {
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},
})
checkPriorities(t, tree)
// Case 2: Mirror case: /a/b and /:p/b/, request /a/b/
// GET /a/b/ should match /:p/b/ with param p="a", rather than redirecting to /a/b
tree2 := &node{}
routes2 := []string{
"/a/b",
"/:p/b/",
}
for _, route := range routes2 {
tree2.addRoute(route, fakeHandler(route))
}
checkRequests(t, tree2, testRequests{
{"/a/b/", false, "/:p/b/", Params{Param{Key: "p", Value: "a"}}},
{"/a/b", false, "/a/b", nil},
})
checkPriorities(t, tree2)
// Case 3: When no wildcard route matches the exact request,
// TSR should still be recommended for candidate static route
tree3 := &node{}
routes3 := []string{
"/b/",
"/:name/x",
}
for _, route := range routes3 {
tree3.addRoute(route, fakeHandler(route))
}
val := tree3.getValue("/b", nil, getSkippedNodes(), false)
if val.handlers != nil {
t.Errorf("Expected nil handler for '/b', got: %v", val.handlers)
}
if !val.tsr {
t.Errorf("Expected TSR=true for '/b' when '/b/' exists and '/:name/x' does not match")
}
// Case 4: Mirror TSR fallback when no wildcard route matches
tree4 := &node{}
routes4 := []string{
"/a/b",
"/:p/b/x",
}
for _, route := range routes4 {
tree4.addRoute(route, fakeHandler(route))
}
val4 := tree4.getValue("/a/b/", nil, getSkippedNodes(), false)
if val4.handlers != nil {
t.Errorf("Expected nil handler for '/a/b/', got: %v", val4.handlers)
}
if !val4.tsr {
t.Errorf("Expected TSR=true for '/a/b/' when '/a/b' exists and '/:p/b/x' does not match")
}
// Case 5: Wildcard sibling interaction: /:a/b/ and /:a/b, request /foo/b
// GET /foo/b should match /:a/b with param a="foo", rather than redirecting to /:a/b/
tree5 := &node{}
routes5 := []string{
"/:a/b/",
"/:a/b",
}
for _, route := range routes5 {
tree5.addRoute(route, fakeHandler(route))
}
checkRequests(t, tree5, testRequests{
{"/foo/b", false, "/:a/b", Params{Param{Key: "a", Value: "foo"}}},
{"/foo/b/", false, "/:a/b/", Params{Param{Key: "a", Value: "foo"}}},
})
checkPriorities(t, tree5)
// Case 6: Reverse registration order of wildcard sibling routes
tree6 := &node{}
routes6 := []string{
"/:a/b",
"/:a/b/",
}
for _, route := range routes6 {
tree6.addRoute(route, fakeHandler(route))
}
checkRequests(t, tree6, testRequests{
{"/foo/b", false, "/:a/b", Params{Param{Key: "a", Value: "foo"}}},
{"/foo/b/", false, "/:a/b/", Params{Param{Key: "a", Value: "foo"}}},
})
checkPriorities(t, tree6)
}