在Go中,如何重用ReadCloser?

Cam*_*rzt 2 go

我有一个http请求,我需要检查身体.但是当我这样做时,请求失败了.我假设这与读者需要重置有关,但谷歌搜索go ioutil reset ReadCloser没有变成任何看起来很有希望的东西.

c是一个*middleware.Context, c.Req.Request是一个http.Request, c.Req.Request.Body是一个io.ReadCloser

contents, _ := ioutil.ReadAll(c.Req.Request.Body)
log.Info("Request: %s", string(contents))
proxy.ServeHTTP(c.RW(), c.Req.Request)
Run Code Online (Sandbox Code Playgroud)

特别是我得到的错误是 http: proxy error: http: ContentLength=133 with Body length 0

Jim*_*imB 8

您无法重置它,因为您已经从中读取过,并且流中没有任何内容.

你可以做的是获取你已经拥有的缓冲字节,并用新的替换Body io.ReadCloser

contents, _ := ioutil.ReadAll(c.Req.Request.Body)
log.Info("Request: %s", string(contents))
c.Req.Request.Body = ioutil.NopCloser(bytes.NewReader(contents))
proxy.ServeHTTP(c.RW(), c.Req.Request)
Run Code Online (Sandbox Code Playgroud)