我在 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" } ] } ] }
1 回答

浮云間
TA貢獻1829條經驗 獲得超4個贊
我正在使用 http.DetectContentType 返回請求的內容類型,但它在每個場景中都返回 text/plain 。
application/json
您會發現它根本不關心或類似,并且它返回text/plain
任何看起來非二進制的內容(并且之前與 一樣不匹配text/html
)。
換句話說:這是不適合這項工作的工具。正確的方法是客戶端使用標頭指定發送的內容類型Content-Type
,而不是讓服務器猜測內容類型。
- 1 回答
- 0 關注
- 274 瀏覽
添加回答
舉報
0/150
提交
取消