1
0
mirror of https://github.com/golang/go synced 2024-11-20 00:34:43 -07:00

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
This commit is contained in:
Andrew Gerrand 2011-11-17 11:42:25 +11:00
parent 3ec82f6e09
commit 0b1bcf8f94
2 changed files with 35 additions and 1 deletions

View File

@ -22,13 +22,19 @@ import (
// A Dir implements http.FileSystem using the native file // A Dir implements http.FileSystem using the native file
// system restricted to a specific directory tree. // system restricted to a specific directory tree.
//
// An empty Dir is treated as ".".
type Dir string type Dir string
func (d Dir) Open(name string) (File, error) { func (d Dir) Open(name string) (File, error) {
if filepath.Separator != '/' && strings.IndexRune(name, filepath.Separator) >= 0 { if filepath.Separator != '/' && strings.IndexRune(name, filepath.Separator) >= 0 {
return nil, errors.New("http: invalid character in file path") 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 { if err != nil {
return nil, err return nil, err
} }

View File

@ -208,6 +208,20 @@ func TestDirJoin(t *testing.T) {
test(Dir("/etc/hosts"), "../") 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) { func TestServeFileContentType(t *testing.T) {
const ctype = "icecream/chocolate" const ctype = "icecream/chocolate"
override := false 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) { func TestServeFileWithContentEncoding(t *testing.T) {
ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) { ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
w.Header().Set("Content-Encoding", "foo") w.Header().Set("Content-Encoding", "foo")