英文:
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)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论