在 rest api 中,當(dāng) body 設(shè)置為“{}”時,json Decoder 不會產(chǎn)生錯誤。這使得有必要檢查目標(biāo)結(jié)構(gòu)是否仍然是nil.我需要檢查庫是否應(yīng)該像這樣工作,或者這是否是它的問題。// Client Side this requestreq, err := http.NewRequest("POST", "url", strings.NewReader("{}") )// Curl equivalent: curl -X POST -d '{}' http://api:8080/r/primitives/multiply// Server sidetype Operands struct { Values []float64 `json:"Values"`}func handler(req *http.Request, res *http.Response) (string, error) { operands := Operands{} err := json.NewDecoder(req.Body).Decode(&operands) if err != nil { res.StatusCode = 400 res.Status = http.StatusText(res.StatusCode) http.StatusText(res.StatusCode) return "", err } operands.Values[0] // It will fail here.}編輯 1:解碼器在生成錯誤的情況下可以正常處理空主體“”,并且可以正常處理像這樣的正確主體:編輯 2:這里的{"Values" : [ 5.0 , 2.0 ]} 問題是對于“{}”主體,它不會返回解碼時出錯,而是將目標(biāo)結(jié)構(gòu)保持為 nil。
1 回答

慕雪6442864
TA貢獻(xiàn)1812條經(jīng)驗 獲得超5個贊
{}
只是一個空的 Json 對象,它可以很好地解碼您的Operands
結(jié)構(gòu),因為結(jié)構(gòu)不需要在Operands
數(shù)組中包含任何內(nèi)容。
您需要自己驗證,例如
err := json.NewDecoder(req.Body).Decode(&operands) if err != nil || len(operands.Values) == 0{
- 1 回答
- 0 關(guān)注
- 156 瀏覽
添加回答
舉報
0/150
提交
取消