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

- First get the file using http.Get
- Extract the filename from the URL by splitting it with “/”, then get the last part
- Create an empty file with the filename
- 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)
}