如何在Golang中复制http.Get(url)请求的响应

问题描述:

I'm trying to use resp, err := http.Get(url) command to write the response to file as well as use the same response to extract links.

After I write the content to a file using resp.Write(f), I cannot use resp.Body for another purpose (for the response from the above url) without making another http.Get request.

I tried resp2 := bytes.NewBuffer(resp). It gives eror as type does not match. I've tried copy as well.

我正在尝试使用 resp,err:= http.Get(url) code> 命令将响应写入文件以及使用相同的响应来提取链接。 p>

使用 resp.Write(f) code>将内容写入文件后,不能将 resp.Body code>用于其他目的 (用于来自上述url的响应)而没有发出另一个 http.Get code>请求。 p>

我尝试了 resp2:= bytes.NewBuffer(resp)。 由于类型不匹配,因此会给出错误。 我也尝试过复制。 p> div>

Assuming the response fits in memory, just create a buffer and use resp.Write, like (untested, basically correct):

var b bytes.Buffer
if err := resp.Write(b); err != nil {
   // handle error
} else {
    // Do something with buffer
}

for code that works with any reader, use: ioutil.ReadAll, which returns a new []byte containing the data that you can then wrap in a bytes.Buffer

httputil has a response dump. https://golang.org/pkg/net/http/httputil/#DumpRequest It will replace the body with an in-memory copy so you can reuse it.