2015-07-20 37 views
3

我想在golang中编写HTTP代理。我使用这个模块代理:https://github.com/elazarl/goproxy。当有人使用我的代理时,它会以http.Response作为输入来调用一个函数。我们称之为“resp”。 resp.Body是一个io.ReadCloser。我可以通过读取方法将它读入[]字节数组中。但是,它的内容已经从resp.Body中消失了。但是我必须返回一个http.Response,并将其读入一个[]字节的数组。我怎样才能做到这一点?读取缓冲区并将其重写到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 
} 

回答

3

你不得不先读身体的各个,这样你就可以正确地关闭它。读完整个机构后,您可以简单地将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)) 
+0

我想这是'NopCloser'与单个o。 – inf

+0

@inf:谢谢:) – JimB

1

这是因为io.Reader行为更象是一个缓冲区,当你读它,你消耗的,在缓冲区中的数据,并留下了一个空的机构。为了解决这个问题,你只需要关闭响应主体并在现在是一个字符串的主体中创建一个新的ReadCloser

import "io/ioutil" 

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

if err != nil { 
    // 
} 

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