-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
70 lines (54 loc) · 1.04 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
package main
import (
"fmt"
"io"
"net/http"
"os"
"strings"
pgbar "github.com/mymmsc/gox/progressbar"
)
type Downloader struct {
io.Reader
bar *pgbar.Bar
}
func NewDownloader(resp *http.Response) *Downloader {
nb := pgbar.NewBar(0, "下载进度", int(resp.ContentLength))
if resp.ContentLength > 10*1024 {
nb.SetUnit("B", "kb", 1024*1024)
}
if resp.ContentLength > 10*1024*1024 {
nb.SetUnit("B", "MB", 1024*1024)
}
return &Downloader{
Reader: resp.Body,
bar: nb,
}
}
func (d *Downloader) Read(p []byte) (n int, err error) {
n, err = d.Reader.Read(p)
d.bar.Add(n)
return n, err
}
func main() {
if len(os.Args) <= 1 {
fmt.Println("xget url <filename>")
}
url := os.Args[1]
us := strings.Split(url, "/")
filename := us[len(us)-1]
if len(os.Args) == 3 {
filename = os.Args[2]
}
resp, err := http.Get(url)
if err != nil {
panic(err)
}
defer resp.Body.Close()
file, err := os.Create(filename)
if err != nil {
panic(err)
}
downloader := NewDownloader(resp)
io.Copy(file, downloader)
file.Close()
}