nos
nos

Reputation: 20872

golang json decode with empty request body

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?

Upvotes: 2

Views: 6025

Answers (1)

Mr_Pink
Mr_Pink

Reputation: 109404

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

Upvotes: 5

Related Questions