In Go, how can I reuse a ReadCloser?

huangapple go评论87阅读模式
英文:

In Go, how can I reuse a ReadCloser?

问题

我有一个需要检查请求主体的HTTP请求。但是当我这样做时,请求失败了。我猜想这可能与需要重置Reader有关,但是在谷歌上搜索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)

具体的错误是 http: proxy error: http: ContentLength=133 with Body length 0

英文:

I have a http request which I need to inspect the body of. But when I do, the request fails. I'm assuming this had to do with the Reader needing to be reset, but googling along the lines of go ioutil reset ReadCloser hasn't turned anything up that looks promising.

c is a *middleware.Context,
c.Req.Request is a http.Request, and
c.Req.Request.Body is an io.ReadCloser

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

Specifically the error I get is http: proxy error: http: ContentLength=133 with Body length 0

答案1

得分: 17

你无法重置它,因为你已经从中读取过,并且流中没有剩余的内容。

你可以做的是使用已有的缓冲字节,用一个新的io.ReadCloser替换Body。

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)
英文:

You can't reset it, because you've already read from it and there's nothing left in the stream.

What you can do is take the buffered bytes you already have, and replace the Body with a new 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)

huangapple
  • 本文由 发表于 2015年11月5日 05:29:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/33532374.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定