feat(router): add MatchTrailingSlash to serve /foo and /foo/ without a redirect

Fixes #4411

RedirectTrailingSlash already detects when the router tree has a route
registered only with (or without) a trailing slash relative to the
request path (nodeValue.tsr). Previously the only thing that could be
done with that information was issue an HTTP redirect.

MatchTrailingSlash reuses the same tsr signal to look up and serve the
alternate-slash route directly, in-process, with no redirect and no
mutation of Request.URL.Path. It takes precedence over
RedirectTrailingSlash when both are enabled.
This commit is contained in:
Iliyas Shamshiden 2026-09-22 14:32:09 +05:00
parent 3b08cd7235
commit 90e5287d7c
2 changed files with 87 additions and 3 deletions

44
gin.go
View File

@ -121,6 +121,14 @@ type Engine struct {
// RedirectTrailingSlash is independent of this option.
RedirectFixedPath bool
// MatchTrailingSlash if enabled, a request for /foo/ is served directly by the
// handler registered for /foo (or vice versa) instead of issuing a redirect.
// The request's URL.Path is left unchanged, so c.Request.URL.Path and c.FullPath()
// still reflect the path that was actually requested.
// When both this and RedirectTrailingSlash are enabled, MatchTrailingSlash takes
// precedence: the route is served directly and no redirect is issued.
MatchTrailingSlash bool
// HandleMethodNotAllowed if enabled, the router checks if another method is allowed for the
// current route, if the current request can not be routed.
// If this is the case, the request is answered with 'Method Not Allowed'
@ -753,9 +761,30 @@ func (engine *Engine) handleHTTPRequest(c *Context) {
return
}
if httpMethod != http.MethodConnect && rPath != "/" {
if value.tsr && engine.RedirectTrailingSlash {
redirectTrailingSlash(c)
return
if value.tsr {
if engine.MatchTrailingSlash {
// value.params may already hold entries filled in by the lookup
// above; reset before reusing the same backing slice so the
// second lookup doesn't append past its capacity.
if c.params != nil {
*c.params = (*c.params)[:0]
}
tsrValue := root.getValue(toggleTrailingSlash(rPath), c.params, c.skippedNodes, unescape)
if tsrValue.handlers != nil {
if tsrValue.params != nil {
c.Params = *tsrValue.params
}
c.handlers = tsrValue.handlers
c.fullPath = tsrValue.fullPath
c.Next()
c.writermem.WriteHeaderNow()
return
}
}
if engine.RedirectTrailingSlash {
redirectTrailingSlash(c)
return
}
}
if engine.RedirectFixedPath && redirectFixedPath(c, root, engine.RedirectFixedPath) {
return
@ -807,6 +836,15 @@ func serveError(c *Context, code int, defaultMessage []byte) {
c.writermem.WriteHeaderNow()
}
// toggleTrailingSlash returns path with its trailing slash added if absent,
// or removed if present.
func toggleTrailingSlash(path string) string {
if length := len(path); length > 0 && path[length-1] == '/' {
return path[:length-1]
}
return path + "/"
}
func redirectTrailingSlash(c *Context) {
req := c.Request
p := req.URL.Path

View File

@ -301,6 +301,52 @@ func TestRouteRedirectTrailingSlash(t *testing.T) {
assert.Equal(t, http.StatusNotFound, w.Code)
}
func TestRouteMatchTrailingSlash(t *testing.T) {
router := New()
router.RedirectFixedPath = false
router.RedirectTrailingSlash = true
router.MatchTrailingSlash = true
router.GET("/path", func(c *Context) {
// The original request path must be left untouched (no redirect happened).
assert.Equal(t, "/path/", c.Request.URL.Path)
c.String(http.StatusOK, c.FullPath())
})
router.GET("/path2/", func(c *Context) { c.String(http.StatusOK, c.FullPath()) })
router.POST("/path3", func(c *Context) { c.String(http.StatusOK, c.FullPath()) })
router.GET("/users/:id/", func(c *Context) { c.String(http.StatusOK, c.Param("id")) })
// A route without a trailing slash is served directly for a request with one.
w := PerformRequest(router, http.MethodGet, "/path/")
assert.Equal(t, http.StatusOK, w.Code)
assert.Empty(t, w.Header().Get("Location"))
assert.Equal(t, "/path", w.Body.String())
// A route with a trailing slash is served directly for a request without one.
w = PerformRequest(router, http.MethodGet, "/path2")
assert.Equal(t, http.StatusOK, w.Code)
assert.Empty(t, w.Header().Get("Location"))
assert.Equal(t, "/path2/", w.Body.String())
w = PerformRequest(router, http.MethodPost, "/path3/")
assert.Equal(t, http.StatusOK, w.Code)
assert.Empty(t, w.Header().Get("Location"))
// Params are still resolved correctly when matched via the toggled path.
w = PerformRequest(router, http.MethodGet, "/users/42")
assert.Equal(t, http.StatusOK, w.Code)
assert.Equal(t, "42", w.Body.String())
// A path with no registered route at all still 404s.
w = PerformRequest(router, http.MethodGet, "/nope/")
assert.Equal(t, http.StatusNotFound, w.Code)
// When both options are enabled, MatchTrailingSlash takes precedence over redirecting.
router.MatchTrailingSlash = false
w = PerformRequest(router, http.MethodGet, "/path/")
assert.Equal(t, "/path", w.Header().Get("Location"))
assert.Equal(t, http.StatusMovedPermanently, w.Code)
}
func TestRouteRedirectFixedPath(t *testing.T) {
router := New()
router.RedirectFixedPath = true