dongya767979565 2017-03-15 17:23
浏览 66
已采纳

golang json解码带有空的请求主体

In the following http handler, I try to distinguish whether the request body is empty

    type Request struct {                                                       
        A    bool  `json:"lala"`                               
        B    bool  `json:"kaka"`                               
        C    int32 `json:"cc"`                           
        D    int32 `json:"dd"`                             
    }                                                                           
    var (                                                                       
        opts    Request                                                         
        hasOpts bool = true                                                     
    )                                                                           
    err = json.NewDecoder(r.Body).Decode(&opts)                                 
    switch {                                                                    
    case err == io.EOF:                                                         
        hasOpts = false                                                         
    case err != nil:                                                            
        return errors.New("Could not get advanced options: " + err.Error()) 
    }          

However, even with r.Body equals '{}', hasOpts is still true. Is this to be expected? In that case, how should I detect empty request body?

  • 写回答

1条回答 默认 最新

  • dongzhucha3999 2017-03-15 17:31
    关注

    Read the body first, to check its content, then unmarshal it:

    body, err := ioutil.ReadAll(r.Body)
    if err != nil {
        return err
    }
    
    if len(body) > 0 {
        err = json.Unmarshal(body, &opts)
        if err != nil {
            return fmt.Errorf("Could not get advanced options: %s", err)
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 delta降尺度方法,未来数据怎么降尺度
  • ¥15 c# 使用NPOI快速将datatable数据导入excel中指定sheet,要求快速高效
  • ¥15 再不同版本的系统上,TCP传输速度不一致
  • ¥15 高德地图点聚合中Marker的位置无法实时更新
  • ¥15 DIFY API Endpoint 问题。
  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程