go - 在 Go 中,如何重用 ReadCloser?

标签 go

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

c 是一个*middleware.Contextc.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/

相关文章:

go - 如何返回 channel

go - 无法解码嵌套的Yaml

go - 如何从嵌套函数修改 struct boolean?

arrays - 为什么我的数组没有增长?

go - 如果我不知道将在哪里托管 Go 包,我应该如何命名它?

go - Golang扫描函数中 "ERROR: IOError: closed stream"如何处理?

templates - 用于源和目标打印的 Golang 模板

go - 如何在 Go 中打印 "enum"的字符串表示形式?

go - 为什么调用用户定义类型的用户定义 String() 会抛出 "not enough arguments in call to BitFlag.String"?

go - 是否可以在 go 中覆盖自动格式化程序