I've got a basic Go server rendering a single page. However, when the page loads, it can't retrieve static assets (style.css, app.js) because they keep being rendered with MIME type 'text/html' instead of their respective types.
I get this error when I load the page:
Resource interpreted as Stylesheet but transferred with MIME type text/html: "http://localhost:8080/static/style.css"
I know the issue has to do with the HTTP Headers and setting the appropriate Content-Type. However, I'm not sure how to do that for assets that the page itself retrieves. Can anyone help me out with this?
func renderTemplate(w http.ResponseWriter, r *http.Request, msg *Message, path string) {
t, err := template.ParseFiles(path)
if err != nil {
http.NotFound(w, r)
}
// problem is here I think
err = t.Execute(w, msg)
if err != nil {
fmt.Println("Error writing to response writer
\b", err)
}
return
}
func mainHandler(w http.ResponseWriter, r *http.Request) {
renderTemplate(w, r, &Message{Title: "What the Fuck is Open?", Text: "Would you like to sort by prominence or distance?"}, HOME)
return
}
create an assetsHandler to deal with static assets requests.
// if you are using grilla/mux
router := mux.NewRouter()
router.HandleFunc("/static/"+`{path:\S+}`, AssetsHandler)
add Content-Type Header
based on assets' suffix:
w.Header().Set("Content-Type", "text/css")
.css
-> text/css
.js
-> text/javascript
...