志空http.Request.Body中render.Bind

Chi empty http.Request.Body in render.Bind

我正在使用 github.com/pressly/chi 构建这个简单的程序,我尝试从 http.Request.Body:

中解码一些 JSON
package main

import (
    "encoding/json"
    "fmt"
    "net/http"

    "github.com/pressly/chi"
    "github.com/pressly/chi/render"
)

type Test struct {
    Name string `json:"name"`
}

func (p *Test) Bind(r *http.Request) error {
    err := json.NewDecoder(r.Body).Decode(p)
    if err != nil {
        return err
    }
    return nil
}

func main() {
    r := chi.NewRouter()

    r.Post("/products", func(w http.ResponseWriter, r *http.Request) {
        var p Test
        // err := render.Bind(r, &p)
        err := json.NewDecoder(r.Body).Decode(&p)

        if err != nil {
            panic(err)
        }

        fmt.Println(p)
    })

    http.ListenAndServe(":8080", r)
}

当我不使用 render.Bind()(来自 "github.com/pressly/chi/render")时,它按预期工作。

但是,当我取消注释行 err := render.Bind(r, &p) 并注释行 err := json.NewDecoder(r.Body).Decode(&p) 时,它会出现 EOF :

恐慌

2017/06/20 22:26:39 http: panic serving 127.0.0.1:39696: EOF

因此 json.Decode() 失败。

我是不是做错了什么,或者 http.Request.Body 在调用 render.Bind() 之前已经在其他地方读取过?

render.Bind的目的是进行解码,执行Bind(r)进行post解码操作。

例如:

type Test struct {
   Name string `json:"name"`
}

func (p *Test) Bind(r *http.Request) error {
   // At this point, Decode is already done by `chi`
   p.Name = p.Name + " after decode"
  return nil
}

如果您只需要 JSON 解码,则解码后无需对解码值执行其他操作。只需使用:

// Use Directly JSON decoder of std pkg
err := json.NewDecoder(r.Body).Decode(&p)

// Use wrapper method from chi DecodeJSON
err := render.DecodeJSON(r.Body, &p)