-
Notifications
You must be signed in to change notification settings - Fork 36
/
http_downloader.go
101 lines (84 loc) · 2.35 KB
/
http_downloader.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
// Helper methods for downloading a file over HTTP
package main
import (
"fmt"
"io"
"io/ioutil"
"net/http"
"os"
"time"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
)
type httpDownloader struct {
downloader
username string
password string
}
func (downloader httpDownloader) Download(remotePath, outputPath string) error {
outFile, err := os.Create(outputPath)
if err != nil {
return err
}
client := http.Client{
Timeout: 15 * time.Second,
}
req, err := http.NewRequest("GET", remotePath, nil)
if err != nil {
return errors.Wrap(err, "failed to create request")
}
if downloader.username != "" && downloader.password != "" {
req.SetBasicAuth(downloader.username, downloader.password)
}
resp, err := client.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode >= 400 {
return fmt.Errorf("bad status code: %v", resp.StatusCode)
}
// Persist to file in 32K chunks, instead of slurping
_, err = io.Copy(outFile, resp.Body)
if err != nil {
return err
}
if err := outFile.Close(); err != nil {
logrus.Errorf("Failed to close file: %v", err)
}
return nil
}
func (downloader httpDownloader) RemoteChecksum(checksumURL string) (string, error) {
timeout := time.Duration(2 * time.Second)
client := http.Client{
Timeout: timeout,
}
req, err := http.NewRequest("GET", checksumURL, nil)
if err != nil {
return "", errors.Wrap(err, "failed to create request")
}
if downloader.username != "" && downloader.password != "" {
req.SetBasicAuth(downloader.username, downloader.password)
}
resp, err := client.Do(req)
if err != nil {
return "", errors.Wrap(err, "failed to get remote md5sum")
}
// Ignore the checksum if it's not found, as assumed by the caller of this function.
if resp.StatusCode == http.StatusNotFound {
logrus.Debugf("MD5 sum not found at: %s", checksumURL)
return "", nil
}
// A non-2xx status code does not cause an error, so we handle it here. https://pkg.go.dev/net/http#Client.Do
if resp.StatusCode >= 400 {
return "", fmt.Errorf("bad status code: %v", resp.StatusCode)
}
logrus.Debugf("Found MD5 sum at: %s", checksumURL)
defer resp.Body.Close()
remoteChecksum, err := ioutil.ReadAll(resp.Body)
if err != nil {
logrus.Debug("Error reading remote checksum")
return "", errors.Wrap(err, "failed to read remote md5sum")
}
return string(remoteChecksum), nil
}