Skip to content

Commit fa1a373

Browse files
humaidqunknwon
andauthored
static: fix infinite redirection when prefix is set (#202)
Co-authored-by: ᴜɴᴋɴᴡᴏɴ <u@gogs.io>
1 parent 827b70e commit fa1a373

2 files changed

Lines changed: 19 additions & 1 deletion

File tree

static.go

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -148,8 +148,13 @@ func staticHandler(ctx *Context, log *log.Logger, opt StaticOptions) bool {
148148

149149
// Try to serve index file
150150
if fi.IsDir() {
151-
// Redirect if missing trailing slash.
152151
redirPath := path.Clean(ctx.Req.URL.Path)
152+
// path.Clean removes the trailing slash, so we need to add it back when
153+
// the original path has it.
154+
if strings.HasSuffix(ctx.Req.URL.Path, "/") {
155+
redirPath = redirPath + "/"
156+
}
157+
// Redirect if missing trailing slash.
153158
if !strings.HasSuffix(redirPath, "/") {
154159
http.Redirect(ctx.Resp, ctx.Req.Request, redirPath+"/", http.StatusFound)
155160
return true

static_test.go

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -224,6 +224,19 @@ func Test_Static_Options(t *testing.T) {
224224
}
225225

226226
func Test_Static_Redirect(t *testing.T) {
227+
Convey("Serve static files with prefix without redirect", t, func() {
228+
m := New()
229+
opt := StaticOptions{Prefix: "/public"}
230+
m.Use(Static(currentRoot, opt))
231+
232+
resp := httptest.NewRecorder()
233+
req, err := http.NewRequest("GET", "http://localhost:4000/public/", nil)
234+
So(err, ShouldBeNil)
235+
m.ServeHTTP(resp, req)
236+
237+
So(resp.Code, ShouldEqual, http.StatusNotFound)
238+
})
239+
227240
Convey("Serve static files with redirect", t, func() {
228241
m := New()
229242
m.Use(Static(currentRoot, StaticOptions{Prefix: "/public"}))

0 commit comments

Comments
 (0)