json - 将 "{}"主体解码为结构时,Golang 不会产生错误

标签 json http go

在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/

相关文章:

sql - 向 postgres 查询添加查询参数时出错

java - 访问嵌套在两个 JSON 数组内的 JSON 对象

java - 使用 Jackson 反序列化时禁用标量到字符串的转换

ruby-on-rails - 这个 Rails JSON 身份验证 API(使用 Devise)安全吗?

http - 将 Reader 返回给 http.Response 的函数

go - 不能在 Go 中使用函数作为类型

go - 使用可变参数实现接口(interface)方法

javascript - 填充最后一个输入时 JQuery ajax 调用失败

http - 浏览器何时刷新陈旧的缓存条目?

ios - 即使在 plist 文件上添加临时异常后,在 xcode 版本 9.3 ios 11 中 HTTP 加载失败