How to Download a Large File in Go

Created
Modified

Using io.Copy Function

The io.Copy() function copies from src to dst until either EOF is reached on src or an error occurs. It returns the number of bytes copied and the first error encountered while copying, if any. For example,

package main

import (
  "errors"
  "io"
  "net/http"
  "os"
)

func downloadFile(path, url string) error {

  f, err := os.Create(path)
  if err != nil {
    return err
  }
  defer f.Close()

  resp, err := http.Get(url)
  if err != nil {
    return err
  }
  defer resp.Body.Close()

  if resp.StatusCode != http.StatusOK {
    return errors.New("error")
  }

  _, err = io.Copy(f, resp.Body)
  if err != nil {
    return err
  }

  return nil
}

func main() {

  downloadFile("./go.tar.gz", "https://go.dev/dl/go1.18.1.src.tar.gz")
}

Related Tags