Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/go/7.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
读取缓冲区并在Go中将其重写为http.Response_Http_Go_Proxy - Fatal编程技术网

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

读取缓冲区并在Go中将其重写为http.Response,http,go,proxy,Http,Go,Proxy,我想在golang中编程一个HTTP代理。我将此模块用于代理:。当有人使用我的代理时,它调用一个以http.Response作为输入的函数。让我们称之为“resp”。resp.Body是一个io.ReadCloser。我可以使用它的read方法将其读入[]字节数组。但随后它的内容就从各自的身体里消失了。但是我必须返回一个http.Response,返回的主体是我读入[]字节数组的。我该怎么做 您好 马克斯 我的代码: proxy.OnResponse().DoFunc(func(resp *ht

我想在golang中编程一个HTTP代理。我将此模块用于代理:。当有人使用我的代理时,它调用一个以http.Response作为输入的函数。让我们称之为“resp”。resp.Body是一个io.ReadCloser。我可以使用它的read方法将其读入[]字节数组。但随后它的内容就从各自的身体里消失了。但是我必须返回一个http.Response,返回的主体是我读入[]字节数组的。我该怎么做

您好

马克斯

我的代码:

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
}

你必须先阅读所有的正文,这样你才能正确地关闭它。一旦读取了整个正文,就可以简单地用缓冲区替换
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))

这是因为,
io.Reader
更像是一个缓冲区,当您读取它时,您已经消耗了缓冲区中的数据,并且留下了一个空的主体。要解决这个问题,您只需关闭responses主体并在主体之外创建一个新的
ReadCloser
,它现在是一个字符串

import "io/ioutil"

readBody, err := ioutil.ReadAll(resp.Body)

if err != nil {
     // 
}

resp.Body.Close()
resp.Body = ioutil.NopCloser(bytes.NewReader(readBody))

我猜它是
nocloser
,只有一个o。