-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathrget.go
235 lines (191 loc) · 4.82 KB
/
rget.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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
package rget
import (
"context"
"fmt"
"io"
"io/ioutil"
"net/http"
"os"
"path"
"path/filepath"
"golang.org/x/sync/errgroup"
)
type Option struct {
Concurrency uint
URL string
OutputDir string
ContentLength int64
Units Units
}
type Unit struct {
RangeStart int64
RangeEnd int64
TempFileName string
DownloadedSize int64
}
func (u *Unit) Write(data []byte) (int, error) {
d := len(data)
u.DownloadedSize += int64(d)
// fmt.Printf("%v is downloaded %v/%v \n",
// u.TempFileName, u.DownloadedSize, u.RangeEnd-u.RangeStart+1)
return d, nil
}
type Units []Unit
func Run(option Option) error {
fmt.Printf("%+v\n", option)
err := option.checkingHeaders()
if err != nil {
return fmt.Errorf("%s", err)
}
option.divide()
tmpDir, err := ioutil.TempDir("", "rget")
if err != nil {
return fmt.Errorf("%s", err)
}
defer os.RemoveAll(tmpDir)
fmt.Println(tmpDir)
err = option.parallelDownload(tmpDir)
if err != nil {
return fmt.Errorf("%s", err)
}
err = option.combine(tmpDir)
if err != nil {
return fmt.Errorf("%s", err)
}
return nil
}
func (o *Option) checkingHeaders() error {
resp, err := http.Head(o.URL)
if err != nil {
return err
}
if resp.Header.Get("Accept-Ranges") == "" {
err := fmt.Errorf("%s : %s cannot support Ranges Requests", o.URL, resp.Request.URL.String())
return err
}
if resp.Header["Accept-Ranges"][0] == "none" {
err := fmt.Errorf("%s : %s cannot support Ranges Requests", o.URL, resp.Request.URL.String())
return err
}
if resp.ContentLength == 0 {
err := fmt.Errorf("%s size is nil", o.URL)
return err
}
redirectURL := resp.Request.URL.String()
o.ContentLength = resp.ContentLength
// keep the redirect URL that accept Ranges Requests because some mirror sites may deny.
// TODO: redirectURL should set by Unit separately.
if o.URL != redirectURL {
o.URL = redirectURL
}
return err
}
//func divide(contentLength int64, concurrency int) Units {
func (o *Option) divide() {
var units []Unit
if o.Concurrency == 0 {
o.Concurrency = 1
}
if o.ContentLength < int64(o.Concurrency) {
o.Concurrency = uint(o.ContentLength)
}
sbyte := o.ContentLength / int64(o.Concurrency)
for i := 0; i < int(o.Concurrency); i++ {
units = append(units, Unit{
RangeStart: int64(i) * sbyte,
RangeEnd: int64((i+1))*sbyte - 1,
TempFileName: fmt.Sprintf("%d_%s", i, path.Base(o.URL)),
})
}
// TODO: should distribute the remainder to each unit
units[len(units)-1].RangeEnd = (o.ContentLength - 1)
o.Units = units
}
func (o *Option) parallelDownload(tmpDir string) error {
fmt.Println("parallelDownload", o.Units)
eg, ctx := errgroup.WithContext(context.Background())
for i := range o.Units {
// https://godoc.org/golang.org/x/sync/errgroup#example-Group--Parallel
// https://golang.org/doc/faq#closures_and_goroutines
i := i
eg.Go(func() error {
return o.downloadWithContext(ctx, i, tmpDir)
})
}
if err := eg.Wait(); err != nil {
return err
}
return nil
}
func (o *Option) downloadWithContext(
ctx context.Context,
i int,
dir string,
) error {
ctx, cancel := context.WithCancel(ctx)
defer cancel()
fmt.Printf("Downloading: %v %+v\n", i, o.Units[i])
//v1.13
req, err := http.NewRequestWithContext(ctx, http.MethodGet, o.URL, nil)
if err != nil {
return fmt.Errorf("Error: %v", err)
}
// add range header
byteRange := fmt.Sprintf("bytes=%d-%d", o.Units[i].RangeStart, o.Units[i].RangeEnd)
fmt.Println(byteRange)
req.Header.Set("Range", byteRange)
client := http.DefaultClient
// TODO: should check resp.StatusCode.
// client.Do cannot seems to return the err when statusCode is 50x etc.
resp, err := client.Do(req)
if err != nil {
fmt.Printf("client err: %s", err)
return fmt.Errorf("Error: %v", err)
}
defer resp.Body.Close()
select {
case <-ctx.Done():
fmt.Printf("Done: %v %+v\n", i, o.Units[i])
return fmt.Errorf("Error: %v", err)
default:
fmt.Println("default:", i, o.Units[i])
}
w, err := os.Create(filepath.Join(dir, o.Units[i].TempFileName))
if err != nil {
return fmt.Errorf("Error: %v", err)
}
defer func() error {
if err := w.Close(); err != nil {
return fmt.Errorf("Error: %v", err)
}
return nil
}()
_, err = io.Copy(w, io.TeeReader(resp.Body, &o.Units[i]))
if err != nil {
return fmt.Errorf("Error: %v", err)
}
return nil
}
func (o *Option) combine(dir string) error {
w, err := os.Create(filepath.Join(o.OutputDir, path.Base(o.URL)))
if err != nil {
return fmt.Errorf("Error: %v", err)
}
defer func() error {
if err := w.Close(); err != nil {
return fmt.Errorf("Error: %v", err)
}
return nil
}()
for _, unit := range o.Units {
r, err := os.Open(filepath.Join(dir, unit.TempFileName))
if err != nil {
return fmt.Errorf("Error: %v", err)
}
_, err = io.Copy(w, r)
if err != nil {
return fmt.Errorf("Error: %v", err)
}
}
return nil
}