【问题标题】:http.ResponseWriter don't set header content typehttp.ResponseWriter 不设置标头内容类型
【发布时间】:2017-01-06 00:54:28
【问题描述】:

我在 Brian W. Kernighan 和 Alan Donovan 的《The Go Programming Language》一书中编写了任务。这是任务№ 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) 中查看开发菜单时,我看到了这个: network menu in debug

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

所以,我有疑问:这是我的错误,或者是 golang 中的错误,或者是正常情况。

【问题讨论】:

  • 根据给出的答案,这是一个印刷错误问题。

标签: http svg go


【解决方案1】:

您必须在编写响应正文之前设置标头。有关详细信息,请参阅ResponseWriter 文档。

另外,还有一个印刷错误。标头名称是“Content-Type”,而不是“ContentType”

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

【讨论】:

  • 哇,谢谢!我一直在寻找这个问题一个多小时!
猜你喜欢
  • 1970-01-01
  • 2019-03-28
  • 2013-04-18
  • 2021-05-23
  • 2013-09-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-05-30
相关资源
最近更新 更多