golang json decode with empty request body

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

golang json decode with empty request body

问题

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

  1. type Request struct {
  2. A bool `json:"lala"`
  3. B bool `json:"kaka"`
  4. C int32 `json:"cc"`
  5. D int32 `json:"dd"`
  6. }
  7. var (
  8. opts Request
  9. hasOpts bool = true
  10. )
  11. err = json.NewDecoder(r.Body).Decode(&opts)
  12. switch {
  13. case err == io.EOF:
  14. hasOpts = false
  15. case err != nil:
  16. return errors.New("Could not get advanced options: " + err.Error())
  17. }

然而,即使r.Body等于'{}'hasOpts仍然为true。这是预期的吗?如果是这样,我应该如何检测空的请求体?

英文:

In the following http handler, I try to distinguish whether the request body is empty

  1. type Request struct {
  2. A bool `json:"lala"`
  3. B bool `json:"kaka"`
  4. C int32 `json:"cc"`
  5. D int32 `json:"dd"`
  6. }
  7. var (
  8. opts Request
  9. hasOpts bool = true
  10. )
  11. err = json.NewDecoder(r.Body).Decode(&opts)
  12. switch {
  13. case err == io.EOF:
  14. hasOpts = false
  15. case err != nil:
  16. return errors.New("Could not get advanced options: " + err.Error())
  17. }

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

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

  1. body, err := ioutil.ReadAll(r.Body)
  2. if err != nil {
  3. return err
  4. }
  5. if len(body) > 0 {
  6. err = json.Unmarshal(body, &opts)
  7. if err != nil {
  8. return fmt.Errorf("无法获取高级选项:%s", err)
  9. }
  10. }
英文:

Read the body first, to check its content, then unmarshal it:

  1. body, err := ioutil.ReadAll(r.Body)
  2. if err != nil {
  3. return err
  4. }
  5. if len(body) > 0 {
  6. err = json.Unmarshal(body, &opts)
  7. if err != nil {
  8. return fmt.Errorf("Could not get advanced options: %s", err)
  9. }
  10. }

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:

确定