-
Notifications
You must be signed in to change notification settings - Fork 1
/
dl_part.go
52 lines (43 loc) · 993 Bytes
/
dl_part.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 main
import (
"fmt"
"io"
"net/http"
"os"
"path"
"sync"
"github.com/schollz/progressbar/v3"
)
type downloadPart struct {
index int
uri string
dir string
filename string
startByte uint64
endByte uint64
}
func (p *downloadPart) downloadPartFilename() string {
return path.Join(p.dir, fmt.Sprintf("download.part%d", p.index))
}
func (p *downloadPart) fetchPart(wg *sync.WaitGroup, bar *progressbar.ProgressBar) {
defer wg.Done()
byteRange := fmt.Sprintf("bytes=%d-%d", p.startByte, p.endByte)
req, _ := http.NewRequest("GET", p.uri, nil)
req.Header.Set("Range", byteRange)
req.Header.Set("User-Agent", "dl/1.0")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return
}
defer resp.Body.Close()
// Create the file
filename := p.downloadPartFilename()
out, err := os.Create(filename)
if err != nil {
return
}
defer out.Close()
// Write the body to file
_, _ = io.Copy(io.MultiWriter(out, bar), resp.Body)
}