英文:
Golang: io.Copy(httpReponseWriter, os.File) vs. http.ServeFile()
问题
在意识到http包有一个内置的ServeFile方法之前,我实现了一个静态处理程序,大致如下:
func StaticHandler(w http.ResponseWriter, r *http.Request) {
filename := mux.Vars(r)["static"] // 使用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)
}
例如,我这样链接我的样式表和图片:
<img href="/image.jpg" />
<link rel="stylesheet" type="text/css" href="/stylesheet.css">
这个方法运行得很好,除了一个问题:浏览器没有应用我的链接样式表(在Chrome、Firefox、Midori中测试)。样式表可以被访问(访问MYSITE/stylesheet.css会显示CSS纯文本),并且图片在页面中正常加载,但是我的页面没有任何样式。
有什么想法是为什么呢?
英文:
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?
答案1
得分: 6
简单回答:头部信息错误。
Go语言会为html、jpg和png文件提供正确的头部信息,但是对于css(和js)文件,头部信息被设置为"text/plain",而不是"text/css"和"text/javascript"。
Go源码显示了相关处理的调用。
无论如何,通过以下方式设置内容类型:
w.Header().Set("Content-Type", "text/css; charset=utf-8")
就可以解决问题了。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论