POST 请求负载的内容类型

Content Type of POST request payload

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

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

为了实现这种条件处理,我使用 http.DetectContentType 来 return 请求的内容类型,但它 returning 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

    }

期望 return 函数 - 内容类型为 application/json 但得到 text/plain

使用 POSTMAN 将请求发送到服务器,Body 是原始的并且 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"
            }
          ]
        }
     ]
  }

I am using http.DetectContentType to return the content type o the request but it is returning text/plain is every scenario.

根据documentation DetectContentType "... implements the algorithm described at https://mimesniff.spec.whatwg.org/判断给定数据的Content-Type。算法主要是处理浏览器可以自行处理的内容类型。

如果你看 at the actual code 你会发现它根本不关心 application/json 或类似的东西,它 returns text/plain 对任何看起来non-binary(之前与 text/html 不匹配)。

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