net/http: don't panic serving dir in ServeFile with empty Request.URL.Path

Updates #30165
Updates #31622

Change-Id: I7a4b91aa7c5c3af8c0b1273cbb42046feddf7d78
Reviewed-on: https://go-review.googlesource.com/c/go/+/180499
Reviewed-by: Emmanuel Odeke <emm.odeke@gmail.com>
Run-TryBot: Emmanuel Odeke <emm.odeke@gmail.com>
TryBot-Result: Gobot Gobot <gobot@golang.org>
This commit is contained in:
Brad Fitzpatrick 2019-06-04 22:26:09 +00:00
parent b3a1205a11
commit 7ed973b4d9
2 changed files with 13 additions and 1 deletions

View file

@ -585,7 +585,7 @@ 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] != '/' {
if url == "" || url[len(url)-1] != '/' {
localRedirect(w, r, path.Base(url)+"/")
return
}

View file

@ -207,6 +207,18 @@ func TestServeFile_DotDot(t *testing.T) {
}
}
// Tests that this doesn't panic. (Issue 30165)
func TestServeFileDirPanicEmptyPath(t *testing.T) {
rec := httptest.NewRecorder()
req := httptest.NewRequest("GET", "/", nil)
req.URL.Path = ""
ServeFile(rec, req, "testdata")
res := rec.Result()
if res.StatusCode != 301 {
t.Errorf("code = %v; want 301", res.Status)
}
}
var fsRedirectTestData = []struct {
original, redirect string
}{