jai*_*ons 1 json http go go-chi
我正在使用github.com/pressly/chi构建这个简单的程序,我尝试从以下位置解码一些 JSON http.Request.Body:
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()(from "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)解码后操作。
例如:
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)
| 归档时间: | 
 | 
| 查看次数: | 5507 次 | 
| 最近记录: |