-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprogresstracker.go
More file actions
41 lines (35 loc) · 949 Bytes
/
progresstracker.go
File metadata and controls
41 lines (35 loc) · 949 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
package main
import (
"fmt"
"sync/atomic"
"time"
)
type ProgressTracker struct {
downloaded int64
totalSize int64
done chan struct{}
}
func (pt *ProgressTracker) Add(n int64) {
atomic.AddInt64(&pt.downloaded, n)
}
func (pt *ProgressTracker) Run() {
ticker := time.NewTicker(500 * time.Millisecond)
defer ticker.Stop()
for {
select {
case <-ticker.C:
downloaded := atomic.LoadInt64(&pt.downloaded)
percent := float64(downloaded) / float64(pt.totalSize) * 100
fmt.Printf("\rProgress: %.2f%% (%d/%d MB)", percent, downloaded/1024/1024, pt.totalSize/1024/1024)
case <-pt.done:
// final update when Finish is called
downloaded := atomic.LoadInt64(&pt.downloaded)
percent := float64(downloaded) / float64(pt.totalSize) * 100
fmt.Printf("\rProgress: %.2f%% (%d/%d MB) ✅\n", percent, downloaded/1024/1024, pt.totalSize/1024/1024)
return
}
}
}
func (pt *ProgressTracker) Finish() {
close(pt.done)
}