繁体   English   中英

golang json用空请求体解码

[英]golang json decode with empty request body

在下面的http处理程序中,我尝试区分请求体是否为空

    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()) 
    }          

但是,即使r.Body等于'{}'hasOpts仍然是true 这是预期的吗? 在那种情况下,我应该如何检测空请求体?

首先阅读身体,检查其内容,然后解组它:

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)
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM