-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient.go
114 lines (103 loc) · 2.59 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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
package sys11dbaassdk
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"time"
)
type AuthMode string
const (
AuthModeApiKey AuthMode = "apikey"
AuthModeSSO AuthMode = "sso"
)
type errorMsg struct {
Status string `json:"status"`
Code int `json:"code"`
Message string `json:"msg"`
}
type Client struct {
baseUrl string
apiKey string
user string
client *http.Client
agent string
authMode AuthMode
}
func NewClient(baseurl, apikey, agent string, timeoutSeconds int, authMode AuthMode) (*Client, error) {
client := &Client{
baseUrl: baseurl,
apiKey: apikey,
user: apikey,
agent: agent,
authMode: authMode,
}
client.client = &http.Client{
Timeout: time.Duration(timeoutSeconds) * time.Second,
}
return client, nil
}
func (c *Client) get(path string, verbose bool) ([]byte, error) {
req, err := http.NewRequest(http.MethodGet, c.baseUrl+path, nil)
if err != nil {
return nil, err
}
return c.doReq(req, verbose)
}
func (c *Client) delete(path string, verbose bool) ([]byte, error) {
req, err := http.NewRequest(http.MethodDelete, c.baseUrl+path, nil)
if err != nil {
return nil, err
}
return c.doReq(req, verbose)
}
func (c *Client) post(path string, data []byte, verbose bool) ([]byte, error) {
req, err := http.NewRequest(http.MethodPost, c.baseUrl+path, bytes.NewReader(data))
req.Header.Set("Content-Type", "application/json")
if err != nil {
return nil, err
}
return c.doReq(req, verbose)
}
func (c *Client) patch(path string, data []byte, verbose bool) ([]byte, error) {
req, err := http.NewRequest(http.MethodPatch, c.baseUrl+path, bytes.NewReader(data))
req.Header.Set("Content-Type", "application/json")
if err != nil {
return nil, err
}
return c.doReq(req, verbose)
}
func (c *Client) doReq(req *http.Request, verbose bool) ([]byte, error) {
req.Header.Add("Accept", "application/json")
if c.authMode == AuthModeApiKey {
req.Header.Add("x-s11-api-key", c.apiKey)
} else if c.authMode == AuthModeSSO {
req.Header.Add("Authorization", "Bearer "+c.apiKey)
}
req.Header.Add("User-Agent", c.agent)
resp, err := c.client.Do(req)
if err != nil {
return nil, err
}
respBody, err := io.ReadAll(resp.Body)
if verbose {
fmt.Printf("status: %s\nraw response:\n%s\n", resp.Status, respBody)
}
if err != nil {
return nil, err
}
if resp.StatusCode > 299 {
if resp.StatusCode == http.StatusUnauthorized {
return nil, errors.New("authentication failed")
}
e := &errorMsg{}
err := json.Unmarshal(respBody, e)
if err != nil {
return nil, err
}
return respBody, errors.New(e.Message)
}
return respBody, nil
}