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

huangapple go评论162阅读模式
英文:

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)[&quot;static&quot;] // using gorilla/mux
	f, err := os.Open(fmt.Sprintf(&quot;%v/static/%v&quot;, 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:

&lt;img href=&quot;/image.jpg&quot; /&gt;
&lt;link rel=&quot;stylesheet&quot; type=&quot;text/css&quot; href=&quot;/stylesheet.css&quot;&gt;

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(&quot;Content-Type&quot;, &quot;text/css; charset=utf-8&quot;)

Did the trick.

huangapple
  • 本文由 发表于 2013年10月31日 02:13:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/19690731.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定