How can I efficiently download a large file using Go?

后端 未结 4 1978
悲哀的现实
悲哀的现实 2021-01-29 18:48

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 fi

4条回答
  •  无人及你
    2021-01-29 19:17

    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.

提交回复
热议问题