我正在使用 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
出现 panic :
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)
关于json - 在 render.Bind 中置空 http.Request.Body,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44663496/