Golang Code

Part 1) Download a File (from a URL)

· 191 words · 1 minute read #download #file #url #io #copy #stream #create #http #get #response

This example shows how to download a file from the web on to your local machine. By using io.Copy() and passing the response body directly in we stream the data to the file and avoid having to load it all into the memory - it’s not a problem with small files, but it makes a difference when downloading large files.

We also have an example of downloading large files with progress reports.

package main

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

func main() {

    fileUrl := "https://golangcode.com/images/avatar.jpg"

    err := DownloadFile("avatar.jpg", fileUrl)
    if err != nil {
        panic(err)
    }

}

// DownloadFile will download a url to a local file. It's efficient because it will
// write as it downloads and not load the whole file into 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
}
Image of Author Edd Turtle

Author: Edd Turtle

Edd is the Lead Developer at Hoowla, a prop-tech startup, where he spends much of his time working on production-ready Go and PHP code.

See something which isn't right? You can contribute to this page on GitHub or just let us know in the comments below. Thanks for reading!