From: Andrew Gerrand Date: Thu, 17 Nov 2011 00:42:25 +0000 (+1100) Subject: http: fix serving from CWD with http.ServeFile X-Git-Tag: weekly.2011-11-18~22 X-Git-Url: http://www.git.cypherpunks.su/?a=commitdiff_plain;h=0b1bcf8f94620b34396b3549ea959646e830c7c8;p=gostls13.git http: fix serving from CWD with http.ServeFile http: make Dir("") equivalent to Dir(".") Fixes #2471. R=golang-dev, bradfitz, rsc CC=golang-dev https://golang.org/cl/5370061 --- diff --git a/src/pkg/net/http/fs.go b/src/pkg/net/http/fs.go index 5f91ff5cbf..5aadac17a2 100644 --- a/src/pkg/net/http/fs.go +++ b/src/pkg/net/http/fs.go @@ -22,13 +22,19 @@ import ( // A Dir implements http.FileSystem using the native file // system restricted to a specific directory tree. +// +// An empty Dir is treated as ".". type Dir string func (d Dir) Open(name string) (File, error) { if filepath.Separator != '/' && strings.IndexRune(name, filepath.Separator) >= 0 { return nil, errors.New("http: invalid character in file path") } - f, err := os.Open(filepath.Join(string(d), filepath.FromSlash(path.Clean("/"+name)))) + dir := string(d) + if dir == "" { + dir = "." + } + f, err := os.Open(filepath.Join(dir, filepath.FromSlash(path.Clean("/"+name)))) if err != nil { return nil, err } diff --git a/src/pkg/net/http/fs_test.go b/src/pkg/net/http/fs_test.go index e1a784c1f6..6697189900 100644 --- a/src/pkg/net/http/fs_test.go +++ b/src/pkg/net/http/fs_test.go @@ -208,6 +208,20 @@ func TestDirJoin(t *testing.T) { test(Dir("/etc/hosts"), "../") } +func TestEmptyDirOpenCWD(t *testing.T) { + test := func(d Dir) { + name := "fs_test.go" + f, err := d.Open(name) + if err != nil { + t.Fatalf("open of %s: %v", name, err) + } + defer f.Close() + } + test(Dir("")) + test(Dir(".")) + test(Dir("./")) +} + func TestServeFileContentType(t *testing.T) { const ctype = "icecream/chocolate" override := false @@ -247,6 +261,20 @@ func TestServeFileMimeType(t *testing.T) { } } +func TestServeFileFromCWD(t *testing.T) { + ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) { + ServeFile(w, r, "fs_test.go") + })) + defer ts.Close() + r, err := Get(ts.URL) + if err != nil { + t.Fatal(err) + } + if r.StatusCode != 200 { + t.Fatalf("expected 200 OK, got %s", r.Status) + } +} + func TestServeFileWithContentEncoding(t *testing.T) { ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) { w.Header().Set("Content-Encoding", "foo")