【问题标题】:Google App Engine changes content-type to text/html even though it is set to application/xmlGoogle App Engine 将 content-type 更改为 text/html,即使它设置为 application/xml
【发布时间】:2015-11-27 08:12:25
【问题描述】:

已向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

【问题讨论】:

    标签: google-app-engine go


    【解决方案1】:

    查看https://golang.org/pkg/net/http/#ResponseWriter 中的文档,我引用:

    在调用 WriteHeader(或 Write)后更改标头没有 效果

    现在看看你的代码:

    w.WriteHeader(status)
    w.Header().Set("Content-Type", contentType)
    

    如您所见,您确实是“在调用 WriteHeader 后更改标题”——因此,它“没有效果”。

    所以,请在调用之前之前“更改标题”:

    w.Header().Set("Content-Type", contentType)
    w.WriteHeader(status)
    

    我认为这根本不是应用引擎特有的——它应该适用于 Go 中 http 的任何使用。

    【讨论】:

    • 现在感觉很明显!谢谢
    • @W.K.S,不客气!我希望您现在按照通常的 Stack 礼仪接受这个答案。
    【解决方案2】:

    查看来自http/header的信息:

    WriteHeader 发送带有状态码的 HTTP 响应标头。如果 WriteHeader 没有显式调用,第一次调用 Write 会 触发隐式 WriteHeader(http.StatusOK)。因此显式调用 to WriteHeader 主要用于发送错误码。

    首先尝试设置标题然后发送它

    【讨论】:

      猜你喜欢
      • 2010-10-31
      • 1970-01-01
      • 1970-01-01
      • 2022-01-01
      • 1970-01-01
      • 2012-07-11
      • 1970-01-01
      • 1970-01-01
      • 2019-10-26
      相关资源
      最近更新 更多