]> Cypherpunks repositories - gostls13.git/commitdiff
http: fix serving from CWD with http.ServeFile
authorAndrew Gerrand <adg@golang.org>
Thu, 17 Nov 2011 00:42:25 +0000 (11:42 +1100)
committerAndrew Gerrand <adg@golang.org>
Thu, 17 Nov 2011 00:42:25 +0000 (11:42 +1100)
http: make Dir("") equivalent to Dir(".")

Fixes #2471.

R=golang-dev, bradfitz, rsc
CC=golang-dev
https://golang.org/cl/5370061

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

index 5f91ff5cbf659122eb4faa80c213030818e7c20d..5aadac17a23535401049e52dda1e705a300aac33 100644 (file)
@@ -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
        }
index e1a784c1f6d191776824617c1c5b94160bb7e80b..6697189900ed947ddc943ede45420e289057ba97 100644 (file)
@@ -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")