nos*_*nos 1 json http http-post go
在下面的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())
}
Run Code Online (Sandbox Code Playgroud)
但是,即使是r.Body
equals '{}'
,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)
}
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
3604 次 |
最近记录: |