Json 在render.Bind中设置空http.Request.Body
我正在使用来构建这个简单的程序,在这个程序中,我尝试从Json 在render.Bind中设置空http.Request.Body,json,http,go,go-chi,Json,Http,Go,Go 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 (
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 service 127.0.0.1:39696:EOF
因此,json.Decode()
失败
是我做错了什么,还是在调用render.Bind()
之前,http.Request.Body
已经在其他地方读取了?的目的是执行解码并执行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)
或
实际上,我应该检查
render.Bind
的源代码。。。这就解释了为什么正文
是空的,因为它已经被读取了。无论如何,谢谢你的解决方案!
// Use wrapper method from chi DecodeJSON
err := render.DecodeJSON(r.Body, &p)