Skip to content

Commit ddcf8d4

Browse files
0xmohitbradfitz
authored andcommitted
net/http: redirect if the URL path is a dir & doesn't end in a slash
Fixes #13996 Change-Id: I9b2c7fba0705900aca9a70bc6a2687667a9a976c Reviewed-on: https://go-review.googlesource.com/20128 Reviewed-by: Brad Fitzpatrick <[email protected]> Run-TryBot: Brad Fitzpatrick <[email protected]> TryBot-Result: Gobot Gobot <[email protected]>
1 parent edca4cd commit ddcf8d4

File tree

2 files changed

+27
-0
lines changed

2 files changed

+27
-0
lines changed

src/net/http/fs.go

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -393,6 +393,15 @@ func serveFile(w ResponseWriter, r *Request, fs FileSystem, name string, redirec
393393
}
394394
}
395395

396+
// redirect if the directory name doesn't end in a slash
397+
if d.IsDir() {
398+
url := r.URL.Path
399+
if url[len(url)-1] != '/' {
400+
localRedirect(w, r, path.Base(url)+"/")
401+
return
402+
}
403+
}
404+
396405
// use contents of index.html for directory, if present
397406
if d.IsDir() {
398407
index := strings.TrimSuffix(name, "/") + indexPage

src/net/http/fs_test.go

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -505,6 +505,24 @@ func TestServeFileFromCWD(t *testing.T) {
505505
}
506506
}
507507

508+
// Issue 13996
509+
func TestServeDirWithoutTrailingSlash(t *testing.T) {
510+
e := "/testdata/"
511+
defer afterTest(t)
512+
ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
513+
ServeFile(w, r, ".")
514+
}))
515+
defer ts.Close()
516+
r, err := Get(ts.URL + "/testdata")
517+
if err != nil {
518+
t.Fatal(err)
519+
}
520+
r.Body.Close()
521+
if g := r.Request.URL.Path; g != e {
522+
t.Errorf("got %s, want %s", g, e)
523+
}
524+
}
525+
508526
// Tests that ServeFile doesn't add a Content-Length if a Content-Encoding is
509527
// specified.
510528
func TestServeFileWithContentEncoding_h1(t *testing.T) { testServeFileWithContentEncoding(t, h1Mode) }

0 commit comments

Comments
 (0)