Golang 在将“{}”主体解码为结构时不会产生错误

在 rest api 中,当 body 设置为“{}”时,json Decoder 不会产生错误。这使得有必要检查目标结构是否仍然是nil.


我需要检查库是否应该像这样工作,或者这是否是它的问题。


// Client Side this request

req, err := http.NewRequest("POST", "url", strings.NewReader("{}") )


// Curl equivalent: 

curl -X POST -d '{}' http://api:8080/r/primitives/multiply


// Server side

type 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。


森林海
浏览 109回答 1
1回答

慕雪6442864

{}只是一个空的 Json 对象,它可以很好地解码您的Operands结构,因为结构不需要在Operands数组中包含任何内容。您需要自己验证,例如err := json.NewDecoder(req.Body).Decode(&operands) if err != nil || len(operands.Values) == 0{
打开App,查看更多内容
随时随地看视频慕课网APP