在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:解码器在产生错误的空主体“”上工作正常,并且在像这样的正确主体上工作正常:{"Values": [ 5.0 , 2.0 ]}
编辑 2:这里的问题是,对于“{}”主体,它在解码时不会返回错误,而是将目标结构保持为 nil。
最佳答案
{}
只是一个空的 Json 对象,它可以很好地解码您的 Operands
结构,因为该结构不需要在 中包含任何内容操作数
数组。
您需要自己验证,例如
err := json.NewDecoder(req.Body).Decode(&operands)
if err != nil || len(operands.Values) == 0{
关于json - 将 "{}"主体解码为结构时,Golang 不会产生错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52316045/