go - Golang: CSS files are being sent with Content-Type: text/plain -
i have looked around , haven't found specific after. building api using go's standard library. when serving resource files, css files sent text/plain
when wanting send text/css
.
the console throws info message @ me saying:
resource interpreted stylesheet transferred mime type text/plain: "http://localhost:3000/css/app.css".
main.go
package main import ( "bufio" "log" "net/http" "os" "strings" "text/template" ) func main() { templates := populatetemplates() http.handlefunc("/", func(w http.responsewriter, req *http.request) { requestedfile := req.url.path[1:] template := templates.lookup(requestedfile + ".html") if template != nil { template.execute(w, nil) } else { w.writeheader(404) } }) http.handlefunc("/img/", serveresource) http.handlefunc("/css/", serveresource) log.fatal(http.listenandserve(":3000", nil)) } func serveresource(w http.responsewriter, req *http.request) { path := "public" + req.url.path var contenttype string if strings.hassuffix(path, ".css") { contenttype = "text/css" } else if strings.hassuffix(path, ".png") { contenttype = "image/png" } else { contenttype = "text/plain" } f, err := os.open(path) if err == nil { defer f.close() w.header().add("content type", contenttype) br := bufio.newreader(f) br.writeto(w) } else { w.writeheader(404) } } func populatetemplates() *template.template { result := template.new("templates") basepath := "templates" templatefolder, _ := os.open(basepath) defer templatefolder.close() templatepathraw, _ := templatefolder.readdir(-1) templatepaths := new([]string) _, pathinfo := range templatepathraw { if !pathinfo.isdir() { *templatepaths = append(*templatepaths, basepath+"/"+pathinfo.name()) } } result.parsefiles(*templatepaths...) return result }
i believe sending text/css
. seeing wrong?
the application missing "-" in content type header name. change code to:
w.header().add("content-type", contenttype)
Comments
Post a Comment