-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
97 lines (72 loc) · 1.52 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
92
93
94
95
96
97
package instellar
import (
"fmt"
"io"
"net/http"
"time"
)
const HostURL string = "https://opsmaru.com"
type Client struct {
HostURL string
HTTPClient *http.Client
Token string
Credential CredentialStruct
}
type CredentialStruct struct {
Token string `json:"auth_token"`
}
type AuthResponse struct {
Data struct {
Token string `json:"token"`
} `json:"data"`
}
type AcceptedStates []int
func NewClient(host, token *string) (*Client, error) {
c := Client{
HTTPClient: &http.Client{Timeout: 30 * time.Second},
HostURL: HostURL,
}
if host != nil {
c.HostURL = *host
}
if token == nil {
return &c, nil
}
c.Credential = CredentialStruct{
Token: *token,
}
ar, err := c.Authenticate()
if err != nil {
return nil, err
}
c.Token = ar.Data.Token
return &c, nil
}
func (arr *AcceptedStates) doesNotContain(target int) bool {
for _, num := range *arr {
if num == target {
return false
}
}
return true
}
func (c *Client) doRequest(req *http.Request) ([]byte, error) {
req.Header.Set("Content-Type", "application/json")
if c.Token != "" {
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", c.Token))
}
res, err := c.HTTPClient.Do(req)
if err != nil {
return nil, err
}
defer res.Body.Close()
body, err := io.ReadAll(res.Body)
if err != nil {
return nil, err
}
accepted := AcceptedStates{http.StatusOK, http.StatusCreated}
if accepted.doesNotContain(res.StatusCode) {
return nil, fmt.Errorf("status: %d body: %s", res.StatusCode, body)
}
return body, err
}