如何在 HTTP 中间件处理程序之间重用 *http.Request 的请求正文?

bat*_*zor 3 middleware http go

我使用 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
}
Run Code Online (Sandbox Code Playgroud)

user.Create 返回错误 "unexpected end of JSON input"

其实,在我执行的ioutil.ReadAll
user.Create停止解析JSON,
r.Body有一个空数组[]我怎样才能解决这个问题?

Cer*_*món 5

外部处理程序将请求正文读取到 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)
}
Run Code Online (Sandbox Code Playgroud)

该函数bytes.NewReader()返回io.Reader一个字节切片。该函数ioutil.NopCloser将 转换io.Readerio.ReadCloser所需的r.Body


bat*_*zor 4

最后,我通过以下方式恢复了数据:

r.Body = ioutil.NopCloser(bytes.NewBuffer(b))
Run Code Online (Sandbox Code Playgroud)