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

问题描述 投票:1回答:2

我使用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我可以解决这个问题吗?

http go middleware
2个回答
2
投票

外部处理程序将请求主体读取到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转换为io.ReadCloser所需的r.Body


0
投票

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

r.Body = ioutil.NopCloser(bytes.NewBuffer(b))
© www.soinside.com 2019 - 2024. All rights reserved.