Created
August 26, 2020 04:16
-
-
Save rberrelleza/29daea3dffd20e7a28dd8948b4c2cfbc to your computer and use it in GitHub Desktop.
go downloader with progress bar
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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