forked from heroku/cli
/
request.go
89 lines (81 loc) · 1.75 KB
/
request.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
package main
import (
"crypto/tls"
"crypto/x509"
"encoding/json"
"io"
"io/ioutil"
"net/http"
"os"
"path/filepath"
"strings"
"time"
"github.com/franela/goreq"
)
func init() {
goreq.SetConnectTimeout(15 * time.Second)
goreq.DefaultTransport.(*http.Transport).TLSClientConfig = &tls.Config{RootCAs: getCACerts()}
}
func apiRequestBase(authToken string) *goreq.Request {
req := goreq.Request{
Uri: apiURL(),
ShowDebug: debugging,
Insecure: !shouldVerifyHost(apiURL()),
}
if authToken != "" {
req.AddHeader("Authorization", "Bearer "+authToken)
}
if os.Getenv("HEROKU_HEADERS") != "" {
var h map[string]string
json.Unmarshal([]byte(os.Getenv("HEROKU_HEADERS")), &h)
for k, v := range h {
req.AddHeader(k, v)
}
}
return &req
}
func apiRequest(authToken string) *goreq.Request {
req := apiRequestBase(authToken)
req.AddHeader("Accept", "application/vnd.heroku+json; version=3")
return req
}
func shouldVerifyHost(host string) bool {
return !strings.HasSuffix(host, "herokudev.com")
}
func getCACerts() *x509.CertPool {
certs := x509.NewCertPool()
path := filepath.Join(AppDir(), "cacert.pem")
data, err := ioutil.ReadFile(path)
if err != nil {
downloadCert(path)
data, err = ioutil.ReadFile(path)
if err != nil {
PrintError(err)
return nil
}
}
ok := certs.AppendCertsFromPEM(data)
if !ok {
Warn("Error parsing " + path)
return nil
}
return certs
}
func downloadCert(path string) {
f, err := os.Create(path)
if err != nil {
PrintError(err)
return
}
res, err := goreq.Request{
Uri: "https://raw.githubusercontent.com/bagder/ca-bundle/master/ca-bundle.crt",
ShowDebug: debugging,
}.Do()
if err != nil {
PrintError(err)
return
}
defer res.Body.Close()
defer f.Close()
io.Copy(f, res.Body)
}