dplbf4340
dplbf4340
2016-01-26 13:36
浏览 213
已采纳

如何在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.

图片转代码服务由CSDN问答提供 功能建议

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

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

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

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • douzhao7014
    douzhao7014 2016-01-26 14:06
    已采纳

    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

    点赞 评论
  • dsasd12314
    dsasd12314 2016-01-26 18:51

    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.

    点赞 评论

相关推荐