forked from mariadb-operator/agent
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient.go
103 lines (90 loc) · 2.05 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
package client
import (
"encoding/json"
"fmt"
"net/http"
"net/url"
"time"
"github.com/mariadb-operator/agent/pkg/errors"
)
type Option func(*Client)
func WithHTTPClient(httpClient *http.Client) Option {
return func(c *Client) {
if httpClient == nil {
httpClient = http.DefaultClient
}
c.httpClient = httpClient
}
}
func WithTimeout(timeout time.Duration) Option {
return func(c *Client) {
if timeout == 0 {
timeout = 1 * time.Minute
}
c.httpClient.Timeout = timeout
}
}
func WithKubernetesAuth(auth bool, serviceAccountPath string) Option {
return func(c *Client) {
c.kubernetesAuth = auth
c.kubernetesSA = serviceAccountPath
}
}
type Client struct {
Bootstrap *Bootstrap
GaleraState *GaleraState
Recovery *Recovery
baseUrl *url.URL
httpClient *http.Client
headers map[string]string
kubernetesAuth bool
kubernetesSA string
}
func NewClient(baseUrl string, opts ...Option) (*Client, error) {
url, err := url.Parse(baseUrl)
if err != nil {
return nil, fmt.Errorf("error parsing base URL: %v", err)
}
client := &Client{
baseUrl: url,
httpClient: http.DefaultClient,
headers: make(map[string]string, 0),
kubernetesAuth: false,
kubernetesSA: "",
}
for _, setOpt := range opts {
setOpt(client)
}
client.Bootstrap = &Bootstrap{
Client: client,
}
client.GaleraState = &GaleraState{
Client: client,
}
client.Recovery = &Recovery{
Client: client,
}
return client, nil
}
func (c *Client) do(req *http.Request, v interface{}) error {
res, err := c.httpClient.Do(req)
if err != nil {
return fmt.Errorf("error doing request: %v", err)
}
defer res.Body.Close()
decoder := json.NewDecoder(res.Body)
if res.StatusCode >= 400 {
var apiErr errors.APIError
if err := decoder.Decode(&apiErr); err != nil {
return fmt.Errorf("error decoding body into error: %v", err)
}
return errors.NewError(res.StatusCode, apiErr.Error())
}
if v == nil {
return nil
}
if err := decoder.Decode(&v); err != nil {
return fmt.Errorf("error decoding body: %v", err)
}
return nil
}