1
0
mirror of https://github.com/golang/go synced 2024-11-22 08:54:39 -07:00

http: allow override of Content-Type for ServeFile

R=bradfitz, bradfitzwork
CC=golang-dev
https://golang.org/cl/4368041
This commit is contained in:
Andrew Gerrand 2011-04-06 14:52:42 +10:00
parent 360ab50a9b
commit b44dbff8c8
2 changed files with 40 additions and 14 deletions

View File

@ -134,22 +134,24 @@ func serveFile(w ResponseWriter, r *Request, name string, redirect bool) {
size := d.Size size := d.Size
code := StatusOK code := StatusOK
// use extension to find content type. // If Content-Type isn't set, use the file's extension to find it.
ext := filepath.Ext(name) if w.Header().Get("Content-Type") == "" {
if ctype := mime.TypeByExtension(ext); ctype != "" { ctype := mime.TypeByExtension(filepath.Ext(name))
w.Header().Set("Content-Type", ctype) if ctype == "" {
} else { // read a chunk to decide between utf-8 text and binary
// read first chunk to decide between utf-8 text and binary
var buf [1024]byte var buf [1024]byte
n, _ := io.ReadFull(f, buf[:]) n, _ := io.ReadFull(f, buf[:])
b := buf[:n] b := buf[:n]
if isText(b) { if isText(b) {
w.Header().Set("Content-Type", "text-plain; charset=utf-8") ctype = "text-plain; charset=utf-8"
} else { } else {
w.Header().Set("Content-Type", "application/octet-stream") // generic binary // generic binary
ctype = "application/octet-stream"
} }
f.Seek(0, os.SEEK_SET) // rewind to output whole file f.Seek(0, os.SEEK_SET) // rewind to output whole file
} }
w.Header().Set("Content-Type", ctype)
}
// handle Content-Range header. // handle Content-Range header.
// TODO(adg): handle multiple ranges // TODO(adg): handle multiple ranges

View File

@ -85,6 +85,30 @@ func TestServeFile(t *testing.T) {
} }
} }
func TestServeFileContentType(t *testing.T) {
const ctype = "icecream/chocolate"
override := false
ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
if override {
w.Header().Set("Content-Type", ctype)
}
ServeFile(w, r, "testdata/file")
}))
defer ts.Close()
get := func(want string) {
resp, _, err := Get(ts.URL)
if err != nil {
t.Fatal(err)
}
if h := resp.Header.Get("Content-Type"); h != want {
t.Errorf("Content-Type mismatch: got %q, want %q", h, want)
}
}
get("text-plain; charset=utf-8")
override = true
get(ctype)
}
func getBody(t *testing.T, req Request) (*Response, []byte) { func getBody(t *testing.T, req Request) (*Response, []byte) {
r, err := DefaultClient.Do(&req) r, err := DefaultClient.Do(&req)
if err != nil { if err != nil {