Skip to content

Instantly share code, notes, and snippets.

@gwuah
Last active February 2, 2021 10:01
Show Gist options
  • Save gwuah/7b829ae0fdf0da66577a6542a4a5a0a1 to your computer and use it in GitHub Desktop.
Save gwuah/7b829ae0fdf0da66577a6542a4a5a0a1 to your computer and use it in GitHub Desktop.
file-downloader
package main
import (
"fmt"
"io"
"net/http"
"os"
"strings"
"time"
"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
}
// PrintProgress prints the progress of a file write
func (wc WriteCounter) PrintProgress() {
// Clear the line by using a character return to go back to the start and remove
// the remaining characters by filling it with spaces
fmt.Printf("\r%s", strings.Repeat(" ", 50))
// Return again and print current status of download
// We use the humanize package to print the bytes in a meaningful way (e.g. 10 MB)
fmt.Printf("\rDownloading... %s complete", humanize.Bytes(wc.Total))
}
func DownloadFile(url string, filepath string) error {
h := http.Client{Timeout: 30 * time.Second}
out, err := os.Create(filepath + ".tmp")
if err != nil {
return err
}
defer out.Close()
req, err := http.NewRequest(http.MethodGet, url, nil)
if err != nil {
return err
}
res, err := h.Do(req)
if err != nil {
return err
}
defer res.Body.Close()
_, err = io.Copy(out, io.TeeReader(res.Body, &WriteCounter{}))
if err != nil {
return err
}
fmt.Println()
err = os.Rename(filepath+".tmp", filepath)
if err != nil {
return err
}
return nil
}
func main() {
err := DownloadFile("url", "my_file.pdf")
if err != nil {
panic(err)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment