我使用go-chi作为HTTP路由器,我想在另一个中重用一个方法
func Registration(w http.ResponseWriter, r *http.Request) {
b, err := ioutil.ReadAll(r.Body) // if you delete this line, the user will be created
// ...other code
// if all good then create new user
user.Create(w, r)
}
...
func Create(w http.ResponseWriter, r *http.Request) {
b, err := ioutil.ReadAll(r.Body)
// ...other code
// ... there I get the problem with parse JSON from &b
}
user.Create
返回错误"unexpected end of JSON input"
实际上,在我执行ioutil.ReadAll
之后
user.Create
不再解析JSON,
在r.Body
有一个空的array[]
how我可以解决这个问题吗?
外部处理程序将请求主体读取到EOF。当调用内部处理程序时,没有什么可以从正文中读取。
要解决此问题,请使用先前在外部处理程序中读取的数据还原请求正文:
func Registration(w http.ResponseWriter, r *http.Request) {
b, err := ioutil.ReadAll(r.Body)
// ...other code
r.Body = ioutil.NopCloser(bytes.NewReader(b))
user.Create(w, r)
}
函数bytes.NewReader()
在字节切片上返回io.Reader
。函数ioutil.NopCloser
将io.Reader
转换为io.ReadCloser
所需的r.Body
。
最后,我能够以这种方式恢复数据:
r.Body = ioutil.NopCloser(bytes.NewBuffer(b))