我在 POST 请求中发送 JSON 正文,但 http.DetectContentType 将其识别为文本/纯文本类型。
我希望能够根据内容类型灵活地处理请求有效负载 - if XML {} if JSON {} else {不处理}
为了实现这种条件处理,我使用 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 将请求发送到服务器,Body 作为 raw 和 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"
}
]
}
]
}
浮云间
相关分类