Download a File Using Go

Downloading a file from the Internet using Go is remarkably easy. Especially coupled with concurrency it makes downloading multiple files fast. The following code below shows how to download a single file using Go.

Goal: Download a test image file, the Google logo
https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png

  1. First get the file using http.Get
  2. Extract the filename from the URL by splitting it with “/”, then get the last part
  3. Create an empty file with the filename
  4. Dump the data into the file from the “res” object in step 1
package main

import (
	"fmt"
	"io"
	"log"
	"net/http"
	"os"
	"strings"
)

func main() {
	// 1. Get the file
	url := "https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png"
	res, err := http.Get(url)
	if err != nil {
		log.Println(err)
		return
	}

	// 2. Extract filename
	parts := strings.Split(url, "/")
	filename := parts[len(parts)-1]

	// 3. Create an empty file
	file, err := os.Create(filename)
	if err != nil {
		log.Println(err)
		return
	}

	// 4. Dump the data
	defer res.Body.Close()
	n, err := io.Copy(file, res.Body)
	if err != nil {
		log.Println(err)
		return
	}

	fmt.Printf("wrote: %q, size: %.2f kb\n", filename, float64(n)/1024)
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s