POST请求有效内容的内容类型

soa*_*mya 0 xml rest json http-post go

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

我想灵活地根据其内容类型来处理请求有效负载-如果是XML {}如果是JSON {}否则是{否处理}

为了实现此条件处理,我使用http.DetectContentType返回请求的内容类型,但在每种情况下都将返回文本/纯文本。

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

    }
Run Code Online (Sandbox Code Playgroud)

期望返回函数-内容类型为application / json但获取文本/纯文本

使用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"
            }
          ]
        }
     ]
  }
Run Code Online (Sandbox Code Playgroud)

Ste*_*ich 5

我正在使用http.DetectContentType返回请求的内容类型,但在每种情况下都将返回文本/纯文本。

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

而且,如果您查看 实际的代码,您会发现它根本不在乎application/json或类似,并且会返回text/plain看起来非二进制的任何内容(并且之前没有与匹配text/html)。

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