如何在 HTTP 中间件处理程序之间重用 *http.Request 的请求主体?
How to reuse request body of *http.Request between HTTP middleware handlers?
我使用 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
return错误"unexpected end of JSON input"
其实我执行后ioutil.ReadAll
user.Create
停止解析 JSON,
r.Body
中有一个空数组[]
我该如何解决这个问题?
外部处理程序将请求正文读取到 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()
returns a io.Reader
在一个字节片上。函数 ioutil.NopCloser
将 io.Reader
转换为 r.Body
所需的 io.ReadCloser
。
最后,我通过这种方式恢复了数据:
r.Body = ioutil.NopCloser(bytes.NewBuffer(b))
我使用 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
return错误"unexpected end of JSON input"
其实我执行后ioutil.ReadAll
user.Create
停止解析 JSON,
r.Body
中有一个空数组[]
我该如何解决这个问题?
外部处理程序将请求正文读取到 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()
returns a io.Reader
在一个字节片上。函数 ioutil.NopCloser
将 io.Reader
转换为 r.Body
所需的 io.ReadCloser
。
最后,我通过这种方式恢复了数据:
r.Body = ioutil.NopCloser(bytes.NewBuffer(b))