dpqjvoq9033 2013-05-01 00:51
浏览 77
已采纳

如何在Go中通过管道将HTTP响应传递给文件?

How do I convert the below code to use streams/pipes so that I don't need to read the full content into memory? Something like: http.Get("http://example.com/").Pipe("./data.txt")

package main
import ("net/http";"io/ioutil")

func main() {
        resp, err := http.Get("http://example.com/")
        check(err)
        defer resp.Body.Close()
        body, err := ioutil.ReadAll(resp.Body)
        check(err)
        err = ioutil.WriteFile("./data.txt", body, 0666)
        check(err)
}
func check(e error) {
        if e != nil {
                panic(e)
        }
}
  • 写回答

1条回答 默认 最新

  • duan19913 2013-05-01 01:13
    关注

    How about io.Copy()? Its documentation can be found at: http://golang.org/pkg/io/#Copy

    It's pretty simple, though. Give it an io.Reader and an io.Writer and it copies the data over, one small chunk at a time (e.g. not all in memory at once).

    So you might try writing something like:

    func main() {
      resp, err := http.Get("...")
      check(err)
      defer resp.Body.Close()
      out, err := os.Create("filename.ext")
      if err != nil {
        // panic?
      }
      defer out.Close()
      io.Copy(out, resp.Body)
    }
    

    I haven't tested the above; I just hacked it together quickly from your above example, but it should be close if not on the money.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 vue组件中无法正确接收并处理axios请求
  • ¥15 隐藏系统界面pdf的打印、下载按钮
  • ¥15 MATLAB联合adams仿真卡死如何解决(代码模型无问题)
  • ¥15 基于pso参数优化的LightGBM分类模型
  • ¥15 安装Paddleocr时报错无法解决
  • ¥15 python中transformers可以正常下载,但是没有办法使用pipeline
  • ¥50 分布式追踪trace异常问题
  • ¥15 人在外地出差,速帮一点点
  • ¥15 如何使用canvas在图片上进行如下的标注,以下代码不起作用,如何修改
  • ¥50 vue router 动态路由问题