在Go中,如何重用ReadCloser?

在Go中,如何重用ReadCloser?,go,Go,我有一个http请求,需要检查的主体。但当我这样做时,请求失败了。我假设这与需要重置的读卡器有关,但谷歌搜索“go-ioutil reset-ReadCloser”并没有找到任何有希望的结果 c是一个*中间件, c.Req.Request是一个http.Request,并且 c.Req.Request.Body是一个io.ReadCloser contents, _ := ioutil.ReadAll(c.Req.Request.Body) log.Info("Request: %s", str

我有一个http请求,需要检查的主体。但当我这样做时,请求失败了。我假设这与需要重置的读卡器有关,但谷歌搜索“go-ioutil reset-ReadCloser”并没有找到任何有希望的结果

c
是一个
*中间件,
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)
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)

具体地说,我得到的错误是http:proxy error:http:ContentLength=133,正文长度为0,您无法重置它,因为您已经从中读取了内容,并且流中没有任何内容

您可以做的是获取已有的缓冲字节,并用新的
io.ReadCloser

contents, _ := ioutil.ReadAll(c.Req.Request.Body)
log.Info("Request: %s", string(contents))
proxy.ServeHTTP(c.RW(), c.Req.Request)
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)