Golang – Download files from website

This recipe downloads all kinds of files from website, but there is no progress tracking, only download the file.

package main

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

func downloadFile(filepath, url string) error {
	resp, err := http.Get(url)
	if err != nil {
		return err
	}
	defer resp.Body.Close()

	f, err := os.Create(filepath)
	if err != nil {
		return err
	}
	defer f.Close()

	_, err = io.Copy(f, resp.Body)
	if err != nil {
		return err
	}
	return nil
}

func main() {
	e := downloadFile("centos.torrent", "http://mirror.nus.edu.sg/centos/7.8.2003/isos/x86_64/CentOS-7-x86_64-LiveKDE-2003.torrent")
	if e != nil {
		log.Fatal(e)
	}
}

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 )

Google photo

You are commenting using your Google 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