google-app-engine - Google App Engine 将内容类型更改为 text/html,即使它设置为 application/xml

标签 google-app-engine go

这个问题有人问过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/

相关文章:

python - 使用 Google App Engine 学习 Python 2.7 的最佳方式是什么?

java - Google 应用引擎 - 客观化问题。嵌入式类未更新

google-app-engine - 将应用引擎端点部署到非默认版本

docker - 如何使用 golang 在不同容器中使用 docker-compose env 文件变量?

docker - 获取docker内部Go所有依赖包

sqlite - 如何使用 sqlite3.h 和 cgo 打开一个新的 sqlite3 数据库?

python - 如何获取GAE上某个页面的访问者数量?

google-app-engine - 如何在 Google App Engine 上使用 urllib2 声明超时?

csv - 同时创建和写入两个CSV golang

mysql - 在 golang 中显示数据库的结果