【问题标题】:Content Type of POST request payloadPOST 请求负载的内容类型
【发布时间】:2019-06-17 15:31:39
【问题描述】:

我在我的 POST 请求中发送 JSON 正文,但 http.DetectContentType 将其识别为文本/纯文本类型。

我希望根据内容类型灵活处理请求负载 - if XML {} if JSON {} else {NO Processing}

为了实现这种条件处理,我使用 http.DetectContentType 返回请求的内容类型,但它返回的是 text/plain 是每个场景。

func Test(w http.ResponseWriter, r *http.Request) *ErrorObject {

        reqBuffer := make([]byte, 512)
        _, err := r.Body.Read(reqBuffer)
        if err != nil {

    return ErrorObject{}.New(1, err, nil)
}

contentType := GetContentType(reqBuffer)
fmt.Printf(contentType)

    if contentType == "application/xml" || contentType == "text/xml" {
    w.Header().Set("Content-Type", "application/xml; charset=UTF-8") ...}
    if contentType == "application/json" || contentType == "text/json" {
    w.Header().Set("Content-Type", "application/json; charset=UTF-8") ... } 
    else return Invalid Request Type error
} 

   func GetContentType(buffer []byte) string {

       fmt.Println(string(buffer))
       contentType := http.DetectContentType(buffer)
       fmt.Printf(contentType)
       return contentType

    }

期望返回函数 - 内容类型为 application/json 但获取 text/plain

使用 POSTMAN 以原始和 JSON 格式向服务器发送请求

    {
      "data": [
         {
           "group": "TEST",
           "name": "TEST",
           "released": true,
           "version": 1,
           "teststeps": [
              {
                   "bin": 32,
                   "comment": "PAA",
                   "dataType": "J",
                   "format": "R6.2",
                   "id": "PAA3",
                   "osg": 8,
                   "usg": 0
              }
            ],
           "parameters": [
              {
                  "comment": "test",
                  "description": "test",
                  "format": "R7.0",
                  "id": 1,
                  "teststepId": "PAA",
                  "value": 30,
                  "type": "teststep"
            }
          ]
        }
     ]
  }

【问题讨论】:

  • 您是否在 Postman 请求标头中添加了“Content-Type : application/json”?
  • 在发送请求时正确设置 Content-Type 标头通常是客户端的责任。您根本不需要检测它。

标签: json xml rest go http-post


【解决方案1】:

我正在使用 http.DetectContentType 来返回请求的内容类型,但它返回的是 text/plain 是每个场景。

根据documentationDetectContentType“...实现https://mimesniff.spec.whatwg.org/中描述的算法来确定给定数据的Content-Type”。该算法主要用于处理浏览器可以自行处理的内容类型。

如果您查看at the actual code,您会发现它根本不关心application/json 或类似的东西,它会为任何看起来非二进制的东西返回text/plain(并且之前与@ 不匹配) 987654327@).

换句话说:这是适合这项工作的错误工具。正确的方法是让客户端使用Content-Type 标头指定发送的内容类型,而不是让服务器猜测内容的类型。

【讨论】:

  • 感谢您的澄清,但我正在创建一个可以处理这两种类型的 API,因为有两个不同的 Web 应用程序将使用此 API,一个具有 XML 有效负载,另一个具有 JSON。这就是为什么我想在客户端请求处理程序上处理它,如果是 XML 有效负载,我想将它转换为 JSON 并调用我的接受 JSON 格式的核心 API。您可以建议任何其他软件包或库吗?
  • @soamya 正如答案中已经提到的,并且在您不需要库的 cmets 中,您只需检查请求的 Content-Type 标头以找出内容的类型身体。如果发送请求的客户端未提供该标头,则您需要修复该端,而不是后端。
  • 明白了!谢谢!
猜你喜欢
  • 2015-09-07
  • 2014-06-17
  • 1970-01-01
  • 2016-09-04
  • 2013-09-09
  • 2015-02-18
  • 1970-01-01
  • 2021-06-01
  • 2021-07-30
相关资源
最近更新 更多