Merge 5793a439a54ff3119e046b169525f50cac89e988 into 0f09c3a9b4626d9fe9979cf4d0521d6ae32ab646

This commit is contained in:
Wei-Lun Li 2026-11-03 02:18:36 +00:00 committed by GitHub
commit 41e5663d44
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 36 additions and 1 deletions

15
gin.go
View File

@ -9,6 +9,7 @@ import (
"html/template"
"net"
"net/http"
"net/url"
"os"
"path"
"strings"
@ -810,16 +811,28 @@ func serveError(c *Context, code int, defaultMessage []byte) {
func redirectTrailingSlash(c *Context) {
req := c.Request
p := req.URL.Path
// Routing matched the escaped path, so build the redirect from it too;
// otherwise an encoded slash (%2F) would turn into a real path separator.
escaped := c.engine.UseEscapedPath || (c.engine.UseRawPath && req.URL.RawPath != "")
if escaped {
p = req.URL.EscapedPath()
}
if prefix := path.Clean(c.Request.Header.Get("X-Forwarded-Prefix")); prefix != "." {
prefix = sanitizePathChars(prefix)
prefix = removeRepeatedChar(prefix, '/')
p = prefix + "/" + req.URL.Path
p = prefix + "/" + p
}
req.URL.Path = p + "/"
if length := len(p); length > 1 && p[length-1] == '/' {
req.URL.Path = p[:length-1]
}
if escaped {
if unescaped, err := url.PathUnescape(req.URL.Path); err == nil {
req.URL.RawPath = req.URL.Path
req.URL.Path = unescaped
}
}
redirectRequest(c)
}

View File

@ -303,6 +303,28 @@ func TestRouteRedirectTrailingSlash(t *testing.T) {
assert.Equal(t, http.StatusNotFound, w.Code)
}
func TestRouteRedirectTrailingSlashKeepsEscapedPath(t *testing.T) {
for _, useEscapedPath := range []bool{false, true} {
router := New()
router.UseRawPath = !useEscapedPath
router.UseEscapedPath = useEscapedPath
router.GET("/files/:name", func(c *Context) {})
router.GET("/dirs/:name/", func(c *Context) {})
w := PerformRequest(router, http.MethodGet, "/files/a%2Fb/")
assert.Equal(t, http.StatusMovedPermanently, w.Code)
assert.Equal(t, "/files/a%2Fb", w.Header().Get("Location"))
w = PerformRequest(router, http.MethodGet, "/dirs/a%2Fb")
assert.Equal(t, http.StatusMovedPermanently, w.Code)
assert.Equal(t, "/dirs/a%2Fb/", w.Header().Get("Location"))
w = PerformRequest(router, http.MethodGet, "/files/a%2Fb/", header{Key: "X-Forwarded-Prefix", Value: "/api"})
assert.Equal(t, http.StatusMovedPermanently, w.Code)
assert.Equal(t, "/api/files/a%2Fb", w.Header().Get("Location"))
}
}
func TestRouteRedirectFixedPath(t *testing.T) {
router := New()
router.RedirectFixedPath = true