-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathfiledownloader.go
More file actions
101 lines (82 loc) · 1.9 KB
/
filedownloader.go
File metadata and controls
101 lines (82 loc) · 1.9 KB
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
package godownloadthat
import (
"bytes"
"errors"
"fmt"
"io"
"os"
"github.com/valyala/fasthttp"
"github.com/schollz/progressbar/v2"
)
// Downloader implements a downloading client
type Downloader struct {
Client fasthttp.Client
Debug bool
}
// DownloadFiles provides a way to download files from
// urls and save them with the specified fileNames
//
// Downloads concurrently using GoRoutines
func (d *Downloader) DownloadFiles(urls []string, fileNames []string) error {
if len(urls) != len(fileNames) {
return errors.New("The length of URLs doesn't match the length of filenames")
}
done := make(chan []byte, len(urls))
errch := make(chan error, len(urls))
for c, url := range urls {
go func(url string, fileName string) {
result, err := d.downloadFile(url, fileName)
if err != nil {
errch <- err
done <- nil
return
}
done <- result
errch <- err
}(url, fileNames[c])
}
var errStr string
for i := 0; i < len(urls); i++ {
if err := <-errch; err != nil {
errStr = errStr + " " + err.Error()
}
}
var err error
if errStr != "" {
err = errors.New(errStr)
}
return err
}
// Helper function for concurrently downloading files
func (d *Downloader) downloadFile(url string, fileName string) ([]byte, error) {
if d.Debug == true {
defer func() {
fmt.Printf("[Download Complete]: URL: %s, File: %s \n", url, fileName)
}()
}
statusCode, body, err := d.Client.Get(nil, url)
if err != nil {
return nil, err
}
if statusCode != 200 {
return nil, errors.New("URL did not return 200")
}
var out io.Writer;
f, err := os.Create(fileName)
if err != nil {
return nil, err
}
bar := progressbar.NewOptions(
int(len(body)),
progressbar.OptionSetBytes(int(len(body))),
)
out = io.MultiWriter(f, bar)
var data bytes.Buffer
r := bytes.NewReader(body)
_, err = io.Copy(out, r)
print("\n")
if err != nil {
return nil, err
}
return data.Bytes(), nil
}