-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathhttp.go
47 lines (44 loc) · 996 Bytes
/
http.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
package modmake
import (
"context"
"fmt"
"io"
"net/http"
"strings"
)
func Download(url string, location PathString) Task {
url = strings.TrimSpace(url)
if len(url) == 0 {
panic("empty URL")
}
if len(location) == 0 {
panic("empty download location")
}
return func(ctx context.Context) error {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
if err != nil {
return fmt.Errorf("failed to create request: %v", err)
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
return fmt.Errorf("failed to send HTTP request: %v", err)
}
defer func() {
if resp.Body != nil {
_ = resp.Body.Close()
}
}()
if resp.StatusCode != 200 {
return fmt.Errorf("expected status 200 OK, got %s", resp.Status)
}
out, err := location.Create()
if err != nil {
return fmt.Errorf("failed to create download file '%s': %w", location, err)
}
defer func() {
_ = out.Close()
}()
_, err = io.Copy(out, resp.Body)
return err
}
}