How can I efficiently download a large file using Go?

后端 未结 4 2076
悲哀的现实
悲哀的现实 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 18:51

    A more descriptive version of Steve M's answer.

    import (
        "os"
        "net/http"
        "io"
    )
    
    func downloadFile(filepath string, url string) (err error) {
    
      // Create the file
      out, err := os.Create(filepath)
      if err != nil  {
        return err
      }
      defer out.Close()
    
      // Get the data
      resp, err := http.Get(url)
      if err != nil {
        return err
      }
      defer resp.Body.Close()
    
      // Check server response
      if resp.StatusCode != http.StatusOK {
        return fmt.Errorf("bad status: %s", resp.Status)
      }
    
      // Writer the body to file
      _, err = io.Copy(out, resp.Body)
      if err != nil  {
        return err
      }
    
      return nil
    }
    

提交回复
热议问题