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
3
3
import (
4
4
"fmt"
5
5
"net/http"
6
+ "strings"
6
7
7
8
"github.com/go-chi/chi/v5"
8
9
)
@@ -47,13 +48,12 @@ func RedirectSlashes(next http.Handler) http.Handler {
47
48
path = r .URL .Path
48
49
}
49
50
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 , "/" )
50
53
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 )
54
55
}
55
- redirectURL := fmt .Sprintf ("//%s%s" , r .Host , path )
56
- http .Redirect (w , r , redirectURL , 301 )
56
+ http .Redirect (w , r , path , 301 )
57
57
return
58
58
}
59
59
next .ServeHTTP (w , r )
Original file line number Diff line number Diff line change 4
4
"net/http"
5
5
"net/http/httptest"
6
6
"net/url"
7
- "strings"
8
7
"testing"
9
8
10
9
"github.com/go-chi/chi/v5"
@@ -154,7 +153,7 @@ func TestRedirectSlashes(t *testing.T) {
154
153
t .Fatal (body , resp .StatusCode )
155
154
}
156
155
location := resp .Header .Get ("Location" )
157
- if ! strings . HasPrefix ( location , "//" ) || ! strings . HasSuffix ( location , "/accounts/someuser" ) {
156
+ if location != "/accounts/someuser" {
158
157
t .Fatalf ("invalid redirection, should be /accounts/someuser" )
159
158
}
160
159
}
@@ -166,7 +165,7 @@ func TestRedirectSlashes(t *testing.T) {
166
165
t .Fatal (body , resp .StatusCode )
167
166
}
168
167
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" {
170
169
t .Fatalf ("invalid redirection, should be /accounts/someuser?a=1&b=2" )
171
170
}
172
171
}
You can’t perform that action at this time.
0 commit comments