donglan8870 2018-09-13 14:35
浏览 9
已采纳

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

In a rest api, when the body is set to "{}", the json Decoder will not generate an error. This makes it necessary to check if the target struct is still nil.

I need to check if the library is supposed to work like this, or if this is an issue with it.

// 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.
}

Edit 1: The decoder works fine with and empty body "" with the error being generated, and works fine with a correct body like this one: {"Values" : [ 5.0 , 2.0 ]} Edit 2: The issue here is that with a "{}" body, it will not return an error when decoding, instead it will keep the target struct as nil.

  • 写回答

1条回答 默认 最新

  • douluoxiao2286 2018-09-13 15:19
    关注

    {} is just an empty Json object, and it will decode fine to your Operandsstruct, as the struct is not required to have anything in the Operands array.

    You need to validate that yourself, e.g.

    err := json.NewDecoder(req.Body).Decode(&operands)
    if err != nil || len(operands.Values) == 0{
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?