如何重复使用HTTP中间件处理程序之间的 *http.request的主体



我使用go-chi作为http-router,我想在另一种方法内重复使用一种方法

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停止解析,
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()在字节切片上返回io.Reader。函数ioutil.NopCloserio.Reader转换为r.Body所需的io.ReadCloser

最后,我能够以这种方式恢复数据:

r.Body = ioutil.NopCloser(bytes.NewBuffer(b))

最新更新