Golang: remote filesize with progress bar demo

This commit is contained in:
mollusk 2017-09-04 00:21:01 -07:00
parent 1a1f22299f
commit 285796120c

View File

@ -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!")
}