英文:
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)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论