/
main.go
108 lines (93 loc) 路 2.05 KB
/
main.go
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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
package main
import (
"flag"
"fmt"
"io"
"log"
"net/http"
"os"
"path/filepath"
"github.com/charmbracelet/bubbles/progress"
tea "github.com/charmbracelet/bubbletea"
)
var p *tea.Program
type progressWriter struct {
total int
downloaded int
file *os.File
reader io.Reader
onProgress func(float64)
}
func (pw *progressWriter) Start() {
// TeeReader calls pw.Write() each time a new response is received
_, err := io.Copy(pw.file, io.TeeReader(pw.reader, pw))
if err != nil {
if p != nil {
p.Send(progressErrMsg{err})
}
}
}
func (pw *progressWriter) Write(p []byte) (int, error) {
pw.downloaded += len(p)
if pw.total > 0 && pw.onProgress != nil {
pw.onProgress(float64(pw.downloaded) / float64(pw.total))
}
return len(p), nil
}
func getResponse(url string) (*http.Response, error) {
resp, err := http.Get(url)
if err != nil {
log.Fatal(err)
}
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("receiving status of %d for url: %s", resp.StatusCode, url)
}
return resp, nil
}
func main() {
url := flag.String("url", "", "url for the file to download")
flag.Parse()
if *url == "" {
flag.Usage()
os.Exit(1)
}
resp, err := getResponse(*url)
if err != nil {
fmt.Println("could not get response", err)
os.Exit(1)
}
defer resp.Body.Close()
filename := filepath.Base(*url)
file, err := os.Create(filename)
if err != nil {
fmt.Println("could not create file: ", err)
os.Exit(1)
}
defer file.Close()
pw := &progressWriter{
total: int(resp.ContentLength),
file: file,
reader: resp.Body,
onProgress: func(ratio float64) {
if p != nil {
p.Send(progressMsg(ratio))
}
},
}
m := model{
pw: pw,
progress: progress.New(progress.WithDefaultGradient()),
}
// Start the download
go pw.Start()
// Don't add TUI if the header doesn't include content size
// it's impossible see progress without total
if resp.ContentLength > 0 {
// Start Bubble Tea
p = tea.NewProgram(m)
if err := p.Start(); err != nil {
fmt.Println("error running program:", err)
os.Exit(1)
}
}
}