]> Cypherpunks repositories - gostls13.git/commitdiff
net/http: redirect if the URL path is a dir & doesn't end in a slash
authorMohit Agarwal <mohit@sdf.org>
Thu, 3 Mar 2016 18:23:39 +0000 (23:53 +0530)
committerBrad Fitzpatrick <bradfitz@golang.org>
Thu, 24 Mar 2016 02:30:19 +0000 (02:30 +0000)
Fixes #13996

Change-Id: I9b2c7fba0705900aca9a70bc6a2687667a9a976c
Reviewed-on: https://go-review.googlesource.com/20128
Reviewed-by: Brad Fitzpatrick <bradfitz@golang.org>
Run-TryBot: Brad Fitzpatrick <bradfitz@golang.org>
TryBot-Result: Gobot Gobot <gobot@golang.org>

src/net/http/fs.go
src/net/http/fs_test.go

index 7e672a091071d54c872c65c8e6f5529d9c36b82e..5546d375164d44828934f73c268ee7f0e9180c97 100644 (file)
@@ -393,6 +393,15 @@ func serveFile(w ResponseWriter, r *Request, fs FileSystem, name string, redirec
                }
        }
 
+       // redirect if the directory name doesn't end in a slash
+       if d.IsDir() {
+               url := r.URL.Path
+               if url[len(url)-1] != '/' {
+                       localRedirect(w, r, path.Base(url)+"/")
+                       return
+               }
+       }
+
        // use contents of index.html for directory, if present
        if d.IsDir() {
                index := strings.TrimSuffix(name, "/") + indexPage
index 8524df6f3195207fc067e825183b65305fdf7958..9253ebe43aa44c1f7d735de15af47bf9406463c9 100644 (file)
@@ -505,6 +505,24 @@ func TestServeFileFromCWD(t *testing.T) {
        }
 }
 
+// Issue 13996
+func TestServeDirWithoutTrailingSlash(t *testing.T) {
+       e := "/testdata/"
+       defer afterTest(t)
+       ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
+               ServeFile(w, r, ".")
+       }))
+       defer ts.Close()
+       r, err := Get(ts.URL + "/testdata")
+       if err != nil {
+               t.Fatal(err)
+       }
+       r.Body.Close()
+       if g := r.Request.URL.Path; g != e {
+               t.Errorf("got %s, want %s", g, e)
+       }
+}
+
 // Tests that ServeFile doesn't add a Content-Length if a Content-Encoding is
 // specified.
 func TestServeFileWithContentEncoding_h1(t *testing.T) { testServeFileWithContentEncoding(t, h1Mode) }