From 285796120c4ee58948fe0be5b386c35aa2aaf099 Mon Sep 17 00:00:00 2001 From: mollusk Date: Mon, 4 Sep 2017 00:21:01 -0700 Subject: [PATCH] Golang: remote filesize with progress bar demo --- golearn/remote_filesize/remote_filesize.go | 53 ++++++++++++++++++++++ 1 file changed, 53 insertions(+) create mode 100644 golearn/remote_filesize/remote_filesize.go diff --git a/golearn/remote_filesize/remote_filesize.go b/golearn/remote_filesize/remote_filesize.go new file mode 100644 index 0000000..06fbd80 --- /dev/null +++ b/golearn/remote_filesize/remote_filesize.go @@ -0,0 +1,53 @@ +package main + +import ( + "fmt" + "net/http" + "os" + "strconv" + "strings" + "time" + + pb "gopkg.in/cheggaaa/pb.v1" +) + +func main() { + url := "https://repo.voidlinux.eu/live/current/void-live-x86_64-20170220-lxde.iso" + + // we are interested in getting the file or object name + // so take the last item from the slice + subStringsSlice := strings.Split(url, "/") + fileName := subStringsSlice[len(subStringsSlice)-1] + + resp, err := http.Head(url) + if err != nil { + fmt.Println(err) + os.Exit(1) + } + + // Is our request ok? + + if resp.StatusCode != http.StatusOK { + fmt.Println(resp.Status) + os.Exit(1) + // exit if not ok + } + + // the Header "Content-Length" will let us know + // the total file size to download + size, _ := strconv.Atoi(resp.Header.Get("Content-Length")) + downloadSize := int(size) + bytesTokilobytes := downloadSize / 1024 / 1024 + + fmt.Println("Will be downloading ", fileName, " of ", bytesTokilobytes, " MegaBytes.") + + count := bytesTokilobytes + bar := pb.StartNew(count) + for i := 0; i < count; i++ { + bar.Increment() + bar.ShowTimeLeft = true + time.Sleep(time.Millisecond) + } + bar.FinishPrint("The End!") + +}