Skip to content

Instantly share code, notes, and snippets.

@rberrelleza
Created August 26, 2020 04:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rberrelleza/29daea3dffd20e7a28dd8948b4c2cfbc to your computer and use it in GitHub Desktop.
Save rberrelleza/29daea3dffd20e7a28dd8948b4c2cfbc to your computer and use it in GitHub Desktop.
go downloader with progress bar
package main
import (
"io"
"net/http"
"os"
"github.com/cheggaaa/pb/v3"
)
type progress struct {
Total int
Pb *pb.ProgressBar
}
func (p *progress) Write(data []byte) (int, error) {
n := len(data)
p.Pb.Add(int(n))
return n, nil
}
func downloadFile(filepath string, url string) error {
out, err := os.Create(filepath + ".tmp")
if err != nil {
return err
}
// Get the data
resp, err := http.Get(url)
if err != nil {
out.Close()
return err
}
defer resp.Body.Close()
bar := pb.Simple.New(int(resp.ContentLength))
bar.Set(pb.Bytes, true)
bar.Set(pb.SIBytesPrefix, true)
var p = &progress{
Pb: bar.Start(),
}
if _, err = io.Copy(out, io.TeeReader(resp.Body, p)); err != nil {
out.Close()
return err
}
if err = os.Rename(filepath+".tmp", filepath); err != nil {
return err
}
return nil
}
func main() {
if err := downloadFile("okteto.exe", "https://github.com/okteto/okteto/releases/download/1.8.16/okteto.exe"); err != nil {
panic(err)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment