这个问题有人问过before但这个答案适用于 python 应用程序。我想知道如何解决 go 应用程序的问题。
我在 Google App Engine 上部署了一个网络服务,供移动客户端使用。使用下面的函数,我以 XML 或 JSON 的形式发送响应(根据客户的要求)
func (api *API) Respond(w http.ResponseWriter, r *http.Request, body interface{}, status int) {
var contentType string
var content []byte
var err error
if r.Header.Get("Accept") == "application/xml" {
contentType = "application/xml; charset=UTF-8"
content, err = xml.Marshal(body)
} else {
contentType = "application/json; charset=UTF-8"
content, err = json.MarshalIndent(body, "", " ")
}
if err != nil {
panic(err)
}
w.WriteHeader(status)
w.Header().Set("Content-Type", contentType)
w.Write(content)
}
然而,无论哪种情况,客户端设备都会收到 text/html
的 Content-Type。我怎样才能解决这个问题?这是我的应用程序的 app.yam 文件:
application: wks-api
version: 3
runtime: go
api_version: go1
handlers:
- url: /.*
script: api
最佳答案
查看https://golang.org/pkg/net/http/#ResponseWriter中的文档,我引用:
Changing the header after a call to WriteHeader (or Write) has no effect
现在看看你的代码:
w.WriteHeader(status)
w.Header().Set("Content-Type", contentType)
如您所见,您确实是“在调用 WriteHeader 后更改 header ”——因此,它“没有效果”。
因此,请在调用之前“更改 header ”:
w.Header().Set("Content-Type", contentType)
w.WriteHeader(status)
我认为这根本不是 App Engine 特有的——它应该适用于 Go 中 http
的任何使用。
关于google-app-engine - Google App Engine 将内容类型更改为 text/html,即使它设置为 application/xml,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33952908/