Skip to content

Instantly share code, notes, and snippets.

@inutano
Created July 9, 2019 00:35
Show Gist options
  • Save inutano/74c8f55848424714f48bcf9ac3e6ab21 to your computer and use it in GitHub Desktop.
Save inutano/74c8f55848424714f48bcf9ac3e6ab21 to your computer and use it in GitHub Desktop.
// https://golangcode.com/download-a-file-with-progress/
package main
import (
"fmt"
"io"
"net/http"
"os"
"strings"
"github.com/dustin/go-humanize"
)
type WriteCounter struct {
Total uint64
}
func (wc *WriteCounter) Write(p []byte) (int, error) {
n := len(p)
wc.Total += uint64(n)
wc.PrintProgress()
return n, nil
}
func (wc WriteCounter) PrintProgress() {
fmt.Printf("\r%s", strings.Repeat(" ", 35))
fmt.Printf("\rDownloading, %s complete", humanize.Bytes(wc.Total))
}
func Downloadfile(filepath, url string) error {
out, err := os.Create(filepath + ".tmp")
if err != nil {
return err
}
defer out.Close()
resp, err := http.Get(url)
if err != nil {
return err
}
defer resp.Body.Close()
counter := &WriteCounter{}
_, err = io.Copy(out, io.TeeReader(resp.Body, counter))
if err != nil {
return err
}
fmt.Print("\n")
err = os.Rename(filepath+".tmp", filepath)
if err != nil {
return err
}
return nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment