-
Notifications
You must be signed in to change notification settings - Fork 0
/
dl.go
52 lines (42 loc) · 837 Bytes
/
dl.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
package dl
import (
"errors"
"io"
"net/http"
"os"
"strconv"
)
// Download downloads a file
func Download(url string, dst string, progresser ProgressPrinter) error {
resp, err := http.Get(url)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode == http.StatusNotFound {
return errors.New("resource not found")
}
out, err := os.Create(dst)
if err != nil {
return err
}
defer out.Close()
size, err := strconv.Atoi(resp.Header.Get("Content-Length"))
if err != nil {
size = 0
}
if progresser != nil {
progresser.Before()
}
pw := &progressWriter{Total: uint64(size)}
if progresser != nil {
pw.PrintProgress = progresser.Progress
}
if _, err = io.Copy(out, io.TeeReader(resp.Body, pw)); err != nil {
return err
}
if progresser != nil {
progresser.After()
}
return nil
}