-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
84 lines (73 loc) · 1.31 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
package passkey
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"time"
)
type requester struct {
baseURL string
apiKey string
httpClient *http.Client
}
type Client struct {
tenantID string
requester *requester
}
func New(baseURL, apiKey, tenantID string) *Client {
r := &requester{
baseURL: baseURL,
apiKey: apiKey,
httpClient: &http.Client{
Timeout: 30 * time.Second,
},
}
return &Client{requester: r, tenantID: tenantID}
}
func (r *requester) do(
ctx context.Context,
method string,
path string,
body interface{},
result interface{},
) error {
var payload []byte
if body != nil {
if jb, err := json.Marshal(body); nil != err {
return err
} else {
payload = jb
}
}
fullURL := fmt.Sprintf("%s%s",
r.baseURL,
path)
req, err := http.NewRequestWithContext(
ctx,
method,
fullURL,
bytes.NewBuffer(payload))
if err != nil {
return err
}
req.Header.Add("Content-Type", "application/json")
req.Header.Add("ApiKey", r.apiKey)
resp, err := r.httpClient.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
code := resp.StatusCode
if code < 200 || code >= 300 {
data, err := io.ReadAll(resp.Body)
if err != nil {
return err
}
return errors.New(string(data))
}
return json.NewDecoder(resp.Body).Decode(result)
}