在 Go 中读取缓冲区并将其重写为 http.Response

Max*_*mpf 6 proxy http go

我想用 golang 编写一个 HTTP 代理。我使用此模块作为代理: https: //github.com/elazarl/goproxy。当有人使用我的代理时,它会调用一个以 http.Response 作为输入的函数。我们称之为“resp”。resp.Body 是一个 io.ReadCloser。我可以使用它的 Read 方法将其读入 []byte 数组。但随后它的内容就从 resp.Body 中消失了。但我必须返回一个 http.Response 以及我读入 []byte 数组的正文。我怎样才能做到这一点?

问候,

最大限度

我的代码:

proxy.OnResponse().DoFunc(func(resp *http.Response, ctx *goproxy.ProxyCtx) *http.Response {

   body := resp.Body
   var readBody []byte
   nread, readerr := body.Read(readBody)
   //the body is now empty
   //and i have to return a body
   //with the contents i read.
   //how can i do that?
   //doing return resp gives a Response with an empty body
}
Run Code Online (Sandbox Code Playgroud)

Jim*_*imB 6

您必须首先阅读正文的全部内容,以便正确关闭它。读取整个正文后,您可以简单地将 替换Response.Body为缓冲区。

readBody, err := ioutil.ReadAll(resp.Body)
if err != nil {
    // handle error
}
resp.Body.Close()
// use readBody

resp.Body = ioutil.NopCloser(bytes.NewReader(readBody))
Run Code Online (Sandbox Code Playgroud)