For granular control, such as monitoring progress or managing multiple requests, use grab.NewClient() and grab.NewRequest(destination, url).
Key features for monitoring:
client.Do(req): Starts the download and returns a response object.resp.BytesComplete(): Returns the number of bytes transferred so far.resp.Size: The total size of the file in bytes.resp.Progress(): Returns the progress as a float (0.0 to 1.0).resp.Done: A channel that is closed when the download is complete.resp.Err(): Returns any error encountered during the download process.resp.Filename: The path to the saved file.
package main
import (
"fmt"
"os"
"time"
"github.com/cavaliergopher/grab/v3"
)
func main() {
// create client
client := grab.NewClient()
req, _ := grab.NewRequest(".", "http://www.golang-book.com/public/pdf/gobook.pdf")
// start download
fmt.Printf("Downloading %v...\n", req.URL())
resp := client.Do(req)
fmt.Printf(" %v\n", resp.HTTPResponse.Status)
// start UI loop
t := time.NewTicker(500 * time.Millisecond)
defer t.Stop()
Loop:
for {
select {
case <-t.C:
fmt.Printf(" transferred %v / %v bytes (%.2f%%)\n",
resp.BytesComplete(),
resp.Size,
100*resp.Progress())
case <-resp.Done:
// download is complete
break Loop
}
}
// check for errors
if err := resp.Err(); err != nil {
fmt.Fprintf(os.Stderr, "Download failed: %v\n", err)
os.Exit(1)
}
fmt.Printf("Download saved to ./%v \n", resp.Filename)
}