我有一个 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)
具体来说,我得到的错误是 http: proxy error: http: ContentLength=133 with Body length 0
最佳答案
您无法重置它,因为您已经从中读取过并且流中没有任何内容。
您可以做的是获取您已有的缓冲字节,并用新的 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)
关于go - 在 Go 中,如何重用 ReadCloser?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33532374/