golang json decode with empty request body

huangapple go评论84阅读模式
英文:

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。这是预期的吗?如果是这样,我应该如何检测空的请求体?

英文:

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

得分: 5

首先,阅读请求体以检查其内容,然后对其进行解析:

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("无法获取高级选项:%s", err)
    }
}
英文:

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

huangapple
  • 本文由 发表于 2017年3月16日 01:23:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/42816632.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定