|
| 1 | +package download |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "fmt" |
| 6 | + "io/ioutil" |
| 7 | + "net/http" |
| 8 | + |
| 9 | + "golang.org/x/sync/errgroup" |
| 10 | +) |
| 11 | + |
| 12 | +type Range struct { |
| 13 | + low int |
| 14 | + high int |
| 15 | + proc int |
| 16 | +} |
| 17 | + |
| 18 | +func NewRange(filesize uint, procs, proc int) *Range { |
| 19 | + split := int(filesize) / procs |
| 20 | + return &Range{ |
| 21 | + low: split * (proc - 1), |
| 22 | + high: split * proc, |
| 23 | + } |
| 24 | +} |
| 25 | + |
| 26 | +// Low getter |
| 27 | +func (r *Range) Low() int { |
| 28 | + return r.low |
| 29 | +} |
| 30 | + |
| 31 | +// High getter |
| 32 | +func (r *Range) High() int { |
| 33 | + return r.high |
| 34 | +} |
| 35 | + |
| 36 | +// FetchFileSize fetch content length and set filesize |
| 37 | +func (d *Data) FetchFileSize(URL string) (uint, error) { |
| 38 | + resp, err := http.Head(URL) |
| 39 | + |
| 40 | + if err != nil { |
| 41 | + return 0, err |
| 42 | + } |
| 43 | + |
| 44 | + return uint(resp.ContentLength), nil |
| 45 | +} |
| 46 | + |
| 47 | +// Get contents concurrently |
| 48 | +func (d *Downloader) get(ctx context.Context) *errgroup.Group { |
| 49 | + eg, ctx := errgroup.WithContext(ctx) |
| 50 | + |
| 51 | + for i := 0; i < d.Proc(); i++ { |
| 52 | + i := i |
| 53 | + r := NewRange(d.filesize, d.Proc(), i+1) |
| 54 | + |
| 55 | + eg.Go(func() error { |
| 56 | + req, err := http.NewRequest(http.MethodGet, d.URL().String(), nil) |
| 57 | + if err != nil { |
| 58 | + return err |
| 59 | + } |
| 60 | + |
| 61 | + req.Header.Set("Range", fmt.Sprintf("bytes=%d-%d", r.Low(), r.High())) |
| 62 | + req = req.WithContext(ctx) |
| 63 | + |
| 64 | + resp, err := http.DefaultClient.Do(req) |
| 65 | + if err != nil { |
| 66 | + return err |
| 67 | + } |
| 68 | + |
| 69 | + body, err := ioutil.ReadAll(resp.Body) |
| 70 | + defer resp.Body.Close() |
| 71 | + if err != nil { |
| 72 | + return err |
| 73 | + } |
| 74 | + |
| 75 | + d.data[i] = body |
| 76 | + return nil |
| 77 | + }) |
| 78 | + } |
| 79 | + |
| 80 | + return eg |
| 81 | +} |
0 commit comments