为了账号安全,请及时绑定邮箱和手机立即绑定

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 关注
  • 107 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信