File tree Expand file tree Collapse file tree 2 files changed +7
-8
lines changed
Expand file tree Collapse file tree 2 files changed +7
-8
lines changed Original file line number Diff line number Diff line change @@ -3,6 +3,7 @@ package middleware
33import (
44 "fmt"
55 "net/http"
6+ "strings"
67
78 "github.com/go-chi/chi/v5"
89)
@@ -47,13 +48,12 @@ func RedirectSlashes(next http.Handler) http.Handler {
4748 path = r .URL .Path
4849 }
4950 if len (path ) > 1 && path [len (path )- 1 ] == '/' {
51+ // Trim all leading and trailing slashes (e.g., "//evil.com", "/some/path//")
52+ path = "/" + strings .Trim (path , "/" )
5053 if r .URL .RawQuery != "" {
51- path = fmt .Sprintf ("%s?%s" , path [:len (path )- 1 ], r .URL .RawQuery )
52- } else {
53- path = path [:len (path )- 1 ]
54+ path = fmt .Sprintf ("%s?%s" , path , r .URL .RawQuery )
5455 }
55- redirectURL := fmt .Sprintf ("//%s%s" , r .Host , path )
56- http .Redirect (w , r , redirectURL , 301 )
56+ http .Redirect (w , r , path , 301 )
5757 return
5858 }
5959 next .ServeHTTP (w , r )
Original file line number Diff line number Diff line change 44 "net/http"
55 "net/http/httptest"
66 "net/url"
7- "strings"
87 "testing"
98
109 "github.com/go-chi/chi/v5"
@@ -154,7 +153,7 @@ func TestRedirectSlashes(t *testing.T) {
154153 t .Fatal (body , resp .StatusCode )
155154 }
156155 location := resp .Header .Get ("Location" )
157- if ! strings . HasPrefix ( location , "//" ) || ! strings . HasSuffix ( location , "/accounts/someuser" ) {
156+ if location != "/accounts/someuser" {
158157 t .Fatalf ("invalid redirection, should be /accounts/someuser" )
159158 }
160159 }
@@ -166,7 +165,7 @@ func TestRedirectSlashes(t *testing.T) {
166165 t .Fatal (body , resp .StatusCode )
167166 }
168167 location := resp .Header .Get ("Location" )
169- if ! strings . HasPrefix ( location , "//" ) || ! strings . HasSuffix ( location , "/accounts/someuser?a=1&b=2" ) {
168+ if location != "/accounts/someuser?a=1&b=2" {
170169 t .Fatalf ("invalid redirection, should be /accounts/someuser?a=1&b=2" )
171170 }
172171 }
You can’t perform that action at this time.
0 commit comments