how to make a copy of response of http.Get(url) request in Golang

huangapple go评论95阅读模式
英文:

how to make a copy of response of http.Get(url) request in Golang

问题

我正在尝试使用resp, err := http.Get(url)命令将响应写入文件,并且同时使用相同的响应提取链接。

在使用resp.Write(f)将内容写入文件后,我无法再使用resp.Body来处理来自上述URL的响应,除非进行另一个http.Get请求。

我尝试了resp2 := bytes.NewBuffer(resp),但是会出现类型不匹配的错误。我也尝试了复制操作。

英文:

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.

答案1

得分: 5

假设响应适合内存,只需创建一个缓冲区并使用resp.Write,如下所示(未经测试,基本正确):

var b bytes.Buffer
if err := resp.Write(&b); err != nil {
   // 处理错误
} else {
    // 对缓冲区进行操作
}

对于适用于任何读取器的代码,请使用ioutil.ReadAll,它返回一个包含数据的新的[]byte,然后可以将其包装在bytes.Buffer中。

英文:

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

答案2

得分: 3

httputil有一个响应转储功能。https://golang.org/pkg/net/http/httputil/#DumpRequest
它会用内存中的副本替换请求体,以便您可以重复使用它。

英文:

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.

huangapple
  • 本文由 发表于 2016年1月26日 21:36:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/35015084.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定