-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient.go
91 lines (73 loc) · 1.61 KB
/
client.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
package eyc
import (
"fmt"
"io/ioutil"
"net/http"
"os"
"os/user"
"strings"
"time"
)
// HostURL - Default Core API URL
const HostURL string = "https://api.engineyard.com"
// Client -
type Client struct {
HostURL string
HTTPClient *http.Client
Token string
}
// NewClient -
func NewClient(host, token *string) (*Client, error) {
c := Client{
HTTPClient: &http.Client{Timeout: 10 * time.Second},
// Default Hashicups URL
HostURL: HostURL,
}
if host != nil {
c.HostURL = *host
}
// If token not provided, fetch from ~/.ey-core
if token == nil {
usr, err := user.Current()
if err != nil {
return &c, nil
}
eycore_path := fmt.Sprintf("%s/.ey-core", usr.HomeDir)
eycore_data, err := os.ReadFile(eycore_path)
if err != nil {
return &c, nil
}
eycore_token := strings.Split(string(eycore_data), ": ")[1]
eycore_token = strings.ReplaceAll(eycore_token, "\n", "")
token = &eycore_token
if token == nil {
return &c, nil
}
}
c.Token = *token
return &c, nil
}
func (c *Client) doRequest(req *http.Request, authToken *string) ([]byte, error) {
token := c.Token
if authToken != nil {
token = *authToken
}
req.Header = http.Header{
"Content-Type": []string{"application/json"},
"X-EY-TOKEN": []string{token},
"Accept": []string{"application/vnd.engineyard.v3+json"},
}
res, err := c.HTTPClient.Do(req)
if err != nil {
return nil, err
}
defer res.Body.Close()
body, err := ioutil.ReadAll(res.Body)
if err != nil {
return nil, err
}
if res.StatusCode == 404 {
return nil, fmt.Errorf("status: %d, body: %s", res.StatusCode, body)
}
return body, err
}