在Go中,如何重用ReadCloser?

时间:2015-11-04 21:29:55

标签: go

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

c*middleware.Contextc.Req.Requesthttp.Request,并且 c.Req.Request.Bodyio.ReadCloser

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

具体而言,我得到的错误是http: proxy error: http: ContentLength=133 with Body length 0

1 个答案:

答案 0 :(得分:7)

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

您可以做的是获取已有的缓冲字节,并用新的io.ReadCloser替换Body {/ p>

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)