Skip to content
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 14 additions & 1 deletion gin.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import (
"html/template"
"net"
"net/http"
"net/url"
"os"
"path"
"strings"
Expand Down Expand Up @@ -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)
}

Expand Down
18 changes: 18 additions & 0 deletions routes_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -303,6 +303,24 @@ 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"))
}
}

func TestRouteRedirectFixedPath(t *testing.T) {
router := New()
router.RedirectFixedPath = true
Expand Down
Loading