forked from kubernetes/kops
-
Notifications
You must be signed in to change notification settings - Fork 0
/
http.go
73 lines (63 loc) · 1.51 KB
/
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
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
package fi
import (
"fmt"
"github.com/golang/glog"
"io"
"k8s.io/kops/util/pkg/hashing"
"net/http"
"os"
"path"
)
func DownloadURL(url string, dest string, hash *hashing.Hash) (*hashing.Hash, error) {
if hash != nil {
match, err := fileHasHash(dest, hash)
if err != nil {
return nil, err
}
if match {
return hash, nil
}
}
dirMode := os.FileMode(0755)
err := downloadURLAlways(url, dest, dirMode)
if err != nil {
return nil, err
}
if hash != nil {
match, err := fileHasHash(dest, hash)
if err != nil {
return nil, err
}
if !match {
return nil, fmt.Errorf("downloaded from %q but hash did not match expected %q", url, hash)
}
} else {
hash, err = hashing.HashAlgorithmSHA256.HashFile(dest)
if err != nil {
return nil, err
}
}
return hash, nil
}
func downloadURLAlways(url string, destPath string, dirMode os.FileMode) error {
err := os.MkdirAll(path.Dir(destPath), dirMode)
if err != nil {
return fmt.Errorf("error creating directories for destination file %q: %v", destPath, err)
}
output, err := os.Create(destPath)
if err != nil {
return fmt.Errorf("error creating file for download %q: %v", destPath, err)
}
defer output.Close()
glog.Infof("Downloading %q", url)
response, err := http.Get(url)
if err != nil {
return fmt.Errorf("error doing HTTP fetch of %q: %v", url, err)
}
defer response.Body.Close()
_, err = io.Copy(output, response.Body)
if err != nil {
return fmt.Errorf("error downloading HTTP content from %q: %v", url, err)
}
return nil
}