http.ResponseWriter没有设置头部的内容类型

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

http.ResponseWriter don't set header content type

问题

我写了《The Go Programming Language》这本书中的任务,作者是Brian W. Kernighan和Alan Donovan。这是第3.4号任务。我的请求处理程序如下所示:

func handler(w http.ResponseWriter, r *http.Request) {
    poly(w)
    w.Header().Set("ContentType", "image/svg+xml")
    fmt.Println(w.Header().Get("ContentType"))
}

poly(w)是一个返回Writer中的SVG文件的函数。此外,我检查了ContentType的值,它是"image/svg+xml"

但是,当我在Chrome的开发者工具中查看时(F12),我看到的是这样的:

调试中的网络菜单

当然,我看到的是SVG文件的XML文本,而不是图片。

所以,我有一个问题:这是我的错误,还是Golang的一个错误,还是正常的情况?

英文:

I wrote task from book The Go Programming Language by Brian W. Kernighan, Alan Donovan. It's task № 3.4
my handler of request look like this:

func handler(w http.ResponseWriter, r *http.Request) {
	poly(w)
	w.Header().Set("ContentType", "image/svg+xml")
	fmt.Println(w.Header().Get("ContentType"))
}

poly(w) - it's function that return svg file in Writer.
Also, i cheked value of ContentType, and it's is "image/svg+xml".
But when i look in develop menu in chrome(F12) i see this:
network menu in debug

And, ofcourse, i see xml text of svn file, not a picture.

So, i have question: it's my mistake, or it's bug in golang, or it's normal sutiation.

答案1

得分: 8

你必须在写入响应体之前设置头部信息。请参考ResponseWriter文档了解更多细节。

另外,有一个排版错误。头部名称应为"Content-Type",而不是"ContentType"。

func handler(w http.ResponseWriter, r *http.Request) {
  w.Header().Set("Content-Type", "image/svg+xml")
  poly(w)
}
英文:

You must set the headers before writing the response body. See the ResponseWriter documentation for more details.

Also, there's a typographical error. The header name is "Content-Type", not "ContentType"

func handler(w http.ResponseWriter, r *http.Request) {
  w.Header().Set("Content-Type", "image/svg+xml")
  poly(w)
}

huangapple
  • 本文由 发表于 2017年1月5日 23:55:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/41489300.html
匿名

发表评论

匿名网友

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

确定