登录
首页 >  Golang >  Go问答

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

来源:stackoverflow

时间:2024-04-23 20:27:36 296浏览 收藏

在IT行业这个发展更新速度很快的行业,只有不停止的学习,才不会被行业所淘汰。如果你是Golang学习者,那么本文《将“{}”主体解码为结构时,Golang 不会产生错误》就很适合你!本篇内容主要包括##content_title##,希望对大家的知识积累有所帮助,助力实战开发!

问题内容

在rest api中,当body设置为“{}”时,json解码器不会生成错误。这使得有必要检查目标结构是否仍然是 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 结构体,因为该结构体不需要在 operands 数组中包含任何内容。

您需要自己验证这一点,例如

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

以上就是《将“{}”主体解码为结构时,Golang 不会产生错误》的详细内容,更多关于的资料请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>