|
6 | 6 | "net/http" |
7 | 7 | "os" |
8 | 8 | "path/filepath" |
9 | | - "time" |
| 9 | + |
| 10 | + "github.com/cheggaaa/pb/v3" |
10 | 11 | ) |
11 | 12 |
|
12 | 13 | func DownloadFile(url, dest string) error { |
@@ -41,41 +42,15 @@ func DownloadFile(url, dest string) error { |
41 | 42 | return fmt.Errorf("bad status: %s", resp.Status) |
42 | 43 | } |
43 | 44 |
|
44 | | - // Get file size |
45 | | - size := resp.ContentLength |
46 | | - progress := &ProgressReader{Reader: resp.Body, Total: size} |
47 | | - |
48 | | - // Enable progressbar goroutine |
49 | | - go progress.PrintProgress() |
| 45 | + bar := pb.Full.Start64(resp.ContentLength) |
| 46 | + barReader := bar.NewProxyReader(resp.Body) |
50 | 47 |
|
51 | | - _, err = io.Copy(out, progress) |
| 48 | + _, err = io.Copy(out, barReader) |
52 | 49 | if err != nil { |
53 | 50 | return err |
54 | 51 | } |
55 | 52 |
|
56 | | - return nil |
57 | | -} |
58 | | - |
59 | | -type ProgressReader struct { |
60 | | - io.Reader |
61 | | - Total int64 |
62 | | - Current int64 |
63 | | -} |
64 | | - |
65 | | -func (pr *ProgressReader) Read(p []byte) (int, error) { |
66 | | - n, err := pr.Reader.Read(p) |
67 | | - pr.Current += int64(n) |
68 | | - return n, err |
69 | | -} |
| 53 | + bar.Finish() |
70 | 54 |
|
71 | | -func (pr *ProgressReader) PrintProgress() { |
72 | | - for { |
73 | | - percentage := float64(pr.Current) / float64(pr.Total) * 100 |
74 | | - log.Infof("Downloading... %.2f%% complete", percentage) |
75 | | - if pr.Current >= pr.Total { |
76 | | - log.Info("Download complete") |
77 | | - break |
78 | | - } |
79 | | - time.Sleep(1 * time.Second) |
80 | | - } |
| 55 | + return nil |
81 | 56 | } |
0 commit comments