-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathworker.go
More file actions
54 lines (44 loc) · 1.05 KB
/
Copy pathworker.go
File metadata and controls
54 lines (44 loc) · 1.05 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
package main
import (
"fmt"
"io"
"net/http"
"os"
"time"
)
type RangesHeaders struct {
AcceptRanges string
ContentLength int64
ETag string
}
type Chunk struct {
offset int64
size int64
}
func Download(url string, chunk Chunk, file *os.File) error {
req, err := http.NewRequest(http.MethodGet, url, nil)
if err != nil {
return fmt.Errorf("error creating GET request for url %s: %w", url, err)
}
rangeVal := fmt.Sprintf("bytes=%d-%d", chunk.size*chunk.offset, chunk.size*chunk.offset+chunk.size-1)
req.Header.Set("Range", rangeVal)
client := &http.Client{
Timeout: 10 * time.Second,
}
resp, err := client.Do(req)
if err != nil {
return fmt.Errorf("error sending GET request to %s: %w", url, err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusPartialContent {
return fmt.Errorf("Status code is not okay it is %d\n", resp.StatusCode)
}
pw := PartWriter{
File: file,
Offset: chunk.offset,
}
if _, err := io.Copy(&pw, resp.Body); err != nil {
return err
}
return nil
}