golang json解码为空请求正文

时间:2017-03-15 17:23:13

标签: json http go http-post

在下面的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。这是预期的吗?在那种情况下,我应该如何检测空请求体?

1 个答案:

答案 0 :(得分:3)

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

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)
    }
}
相关问题