Track the progress of downloading file

How to track percentage or bytes download when downloading a file from URL.

Do you have any code you use to make this HTTP GET?

This will detect the os and downloads the code and the unzip it.
But it will not show the progress of downloading.

func DownloadFile(filepath string, url string) error {
    out, err := os.Create(filepath)
    if err != nil {
        return err
    }
    defer out.Close()
    resp, err := http.Get(url)
    if err != nil {
        return err
    }
    defer resp.Body.Close()
    _, err = io.Copy(out, resp.Body)
    if err != nil {
        return err
    }
    return nil
}


Why dump all this code when the only interesting line is this?

resp, err := http.Get(url)

This function is blocking. It returns as soon as it has finished executing the HTTP GET request.

Maybe this blog post can help you:

Here they were using third party package. Is there any way to do with go package itself.

Thanks.

“github.com/dustin/go-humanize” is just a package to write bytes as kB, MB, GB etc. You don’t need what

If it uses other pakages then I have to mention the users who download my pakage that they must have that yo must have http://github.com/dustin/go-humanize this package

What Johan means is that you may change this line to avoid using that package:

// 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))

You may just dump the raw amount of bytes, or write your own formatting function to replace the 3rd party call, e.g.:

//Just print the bytes.
fmt.Printf("\rDownloading... %d complete", wc.Total)
//Or use your custom function.
fmt.Printf("\rDownloading... %s complete", yourFormatterFunction(wc.Total))

There, now you have no dependencies apart from the stdlib.

1 Like

Ok.
Thanks

And a really small replacement for humanize is this function:

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.