Golang中响应Content-type设置为application/json但客户端收到text/plain的问题

Golang中响应Content-type设置为application/json但客户端收到text/plain的问题 在我的Go服务器中,我这样写入响应:

w.WriteHeader(http.StatusOK)
w.Header().Set("content-Type", "application/json")
fmt.Println(w.Header().Get("content-Type"))
w.Write(response)
fmt.Println(w.Header().Get("content-Type"))

但是当我在客户端收到响应时,其内容类型却是 text/plain。 这是怎么回事?


更多关于Golang中响应Content-type设置为application/json但客户端收到text/plain的问题的实战教程也可以访问 https://www.itying.com/category-94-b0.html

3 回复

非常感谢,你真是帮了我大忙了!😛

更多关于Golang中响应Content-type设置为application/json但客户端收到text/plain的问题的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html


请注意 ResponseWriter 中的这条注释:

在调用 WriteHeader(或 Write)之后修改头部映射将不会生效,除非修改的是尾部标头。

这正是您所遇到的情况。

另请参阅此示例,它演示了这一点。

要使您的代码正常工作,请调整调用顺序:

w.Header().Set(“content-Type”, “application/json”)
w.WriteHeader(http.StatusOK)
w.Write(response)

问题出在 WriteHeader 调用过早。一旦调用了 WriteHeader,后续对响应头的修改将不会生效。在你的代码中,先调用了 WriteHeader,然后才设置 Content-Type 头,这导致设置无效。

以下是修正后的代码:

w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
w.Write(response)

注意:Content-Type 头的键是大小写敏感的,虽然 net/http 包会规范化头部字段名,但建议使用标准写法 “Content-Type”。

回到顶部