Download a file from url in Golang

Apr. 4, 2018

Example to download a file from url and save on local

io.Copy() read 32kb (maximum) from input and write to output reapeatly, so dont need worry about memory.

func DownloadFile(filepath string, url string) 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()

    // Write the body to file
    _, err = io.Copy(out, resp.Body)
    if err != nil {
        return err
    }

    return nil
}

reference: Code Example