Golang:io.Copy(httpReponseWriter,os.File)与http.ServeFile()

Before realizing that the http package has a builtin ServeFile method, I implemented a static handler more or less like this:

func StaticHandler(w http.ResponseWriter, r *http.Request) {
    filename := mux.Vars(r)["static"] // using gorilla/mux
    f, err := os.Open(fmt.Sprintf("%v/static/%v", webroot, filename))

    if err != nil {
        http.NotFound(w, r)
        return
    }

    defer f.Close()

    io.Copy(w, f)
}

And, for example, linked my style sheet and images this way:

<img href="/image.jpg" />
<link rel="stylesheet" type="text/css" href="/stylesheet.css">

This worked just fine, except for one thing: my linked stylesheet was not being applied by the browser (tested in Chrome, Firefox, Midori). The stylesheet could be served ( visiting MYSITE/stylesheet.css displayed the css plaintext) and images would load normally in a page, but none of my pages would have any style.

Any ideas as to why?

Simple answer: headers were wrong.

Go will supply correct headers for html, jpgs, and pngs, but css (and js) files are left as "text/plain" rather than "text/css" and "text/javascript".

Go source shows the handling being invoked, I believe.

Anyways, setting the content type via:

w.Header().Set("Content-Type", "text/css; charset=utf-8")

Did the trick.