亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Golang 在將“{}”主體解碼為結構時不會產生錯誤

Golang 在將“{}”主體解碼為結構時不會產生錯誤

Go
森林海 2023-04-04 14:40:07
在 rest api 中,當 body 設置為“{}”時,json Decoder 不會產生錯誤。這使得有必要檢查目標結構是否仍然是nil.我需要檢查庫是否應該像這樣工作,或者這是否是它的問題。// 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 ]} 問題是對于“{}”主體,它不會返回解碼時出錯,而是將目標結構保持為 nil。
查看完整描述

1 回答

?
慕雪6442864

TA貢獻1812條經驗 獲得超5個贊

{}只是一個空的 Json 對象,它可以很好地解碼您的Operands結構,因為結構不需要在Operands數組中包含任何內容。

您需要自己驗證,例如

err := json.NewDecoder(req.Body).Decode(&operands)
if err != nil || len(operands.Values) == 0{


查看完整回答
反對 回復 2023-04-04
  • 1 回答
  • 0 關注
  • 158 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號