如何使用Go有效地下载大文件? [英] How can I efficiently download a large file using Go?

查看:126
本文介绍了如何使用Go有效地下载大文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法使用Go下载一个大文件,直接将内容存储到文件中,而不是将其写入文件之前将其全部存储在内存中?由于文件太大,在将其写入文件之前将其全部存储在内存中将耗尽所有内存。 解决方案

p>我假设你的意思是通过http下载(简单省略错误检查):

  import(net / http ;io;os)
...
out,err:= os.Create(output.txt)
defer out.Close()
。 ..
resp,err:= http.Get(http://example.com/)
推迟resp.Body.Close()
...
n, err:= io.Copy(out,resp.Body)

http.Response的Body是一个Reader ,所以你可以使用任何带读者的功能,例如一次读一个块,而不是一次。在这个特定的情况下, io.Copy()为你做了很多努力。


Is there a way to download a large file using Go that will store the content directly into a file instead of storing it all in memory before writing it to a file? Because the file is so big, storing it all in memory before writing it to a file is going to use up all the memory.

解决方案

I'll assume you mean download via http (error checks omitted for brevity):

import ("net/http"; "io"; "os")
...
out, err := os.Create("output.txt")
defer out.Close()
...
resp, err := http.Get("http://example.com/")
defer resp.Body.Close()
...
n, err := io.Copy(out, resp.Body)

The http.Response's Body is a Reader, so you can use any functions that take a Reader, to, e.g. read a chunk at a time rather than all at once. In this specific case, io.Copy() does the gruntwork for you.

这篇关于如何使用Go有效地下载大文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆