0
空http.Request.Body我使用github.com/pressly/chi建立這個簡單的程序,我嘗試了一些JSON從http.Request.Body
解碼:馳在render.Bind
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' ......這解釋了爲什麼'Body'是空的,因爲它已經是讀。無論如何,謝謝你的解決方案! – jaimelescornichons
@jaimelescornichons不客氣。 – jeevatkm