-
Notifications
You must be signed in to change notification settings - Fork 6
/
client.go
284 lines (244 loc) · 6.03 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
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
package apisix
import (
"bytes"
"context"
"crypto/tls"
"crypto/x509"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"strings"
"time"
"github.com/fatih/color"
"go.uber.org/multierr"
)
var (
ErrNotFound = fmt.Errorf("not found")
ErrStillInUse = errors.New("still in use") // We should use force mode
ErrFunctionDisabled = errors.New("function disabled")
)
type Client struct {
baseURL string
adminKey string
cli *http.Client
}
func newClient(baseURL, adminKey string) *Client {
return &Client{
baseURL: baseURL,
adminKey: adminKey,
cli: &http.Client{
Timeout: 5 * time.Second,
},
}
}
func newClientWithCertificates(baseURL, adminKey string, host string, insecure bool, ca *x509.CertPool, certs []tls.Certificate) *Client {
return &Client{
baseURL: baseURL,
adminKey: adminKey,
cli: &http.Client{
Timeout: 5 * time.Second,
Transport: &http.Transport{
TLSClientConfig: &tls.Config{
InsecureSkipVerify: insecure,
ServerName: host,
RootCAs: ca,
Certificates: certs,
},
},
},
}
}
func (c *Client) setAdminKey(req *http.Request) {
if c.adminKey != "" {
req.Header.Set("X-API-Key", c.adminKey)
}
}
func (c *Client) do(req *http.Request) (*http.Response, error) {
c.setAdminKey(req)
return c.cli.Do(req)
}
func (c *Client) getResource(ctx context.Context, url string) (*item, error) {
var res getResponse
err := makeGetRequest(c, ctx, url, &res)
if err != nil {
return nil, err
}
return &res, nil
}
func (c *Client) listResource(ctx context.Context, url string) (items, error) {
var res listResponse
err := makeGetRequest(c, ctx, url, &res)
if err != nil {
return nil, err
}
return res.List, nil
}
func (c *Client) createResource(ctx context.Context, url string, body []byte) (*item, error) {
var cr createResponse
err := makePutRequest(c, ctx, url, body, &cr)
if err != nil {
return nil, err
}
return &cr, nil
}
func (c *Client) updateResource(ctx context.Context, url string, body []byte) (*item, error) {
var ur updateResponse
err := makePutRequest(c, ctx, url, body, &ur)
if err != nil {
return nil, err
}
return &ur, nil
}
func (c *Client) deleteResource(ctx context.Context, url string) error {
req, err := http.NewRequestWithContext(ctx, http.MethodDelete, url, nil)
if err != nil {
return err
}
resp, err := c.do(req)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusNoContent && resp.StatusCode != http.StatusNotFound {
return handleErrorResponse(resp)
}
return nil
}
func readBody(r io.ReadCloser) (string, error) {
defer r.Close()
data, err := io.ReadAll(r)
if err != nil {
return "", err
}
return string(data), nil
}
// getSchema returns the schema of APISIX object.
//
//nolint:unused
func (c *Client) getSchema(ctx context.Context, url string) (string, error) {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
if err != nil {
return "", err
}
resp, err := c.do(req)
if err != nil {
return "", err
}
defer resp.Body.Close()
body, err := readBody(resp.Body)
if err != nil {
err = multierr.Append(err, fmt.Errorf("read body failed"))
return "", err
}
if resp.StatusCode != http.StatusOK {
if resp.StatusCode == http.StatusNotFound {
return "", ErrNotFound
} else {
err = multierr.Append(err, fmt.Errorf("unexpected status code %d", resp.StatusCode))
err = multierr.Append(err, fmt.Errorf("error message: %s", body))
}
return "", err
}
return body, nil
}
// getList returns a list of string.
//
//nolint:unused
func (c *Client) getList(ctx context.Context, url string) ([]string, error) {
var listResp map[string]interface{}
err := makeGetRequest(c, ctx, url, &listResp)
if err != nil {
return nil, err
}
res := make([]string, 0, len(listResp))
for name := range listResp {
res = append(res, name)
}
return res, nil
}
func (c *Client) validate(ctx context.Context, url string, resource interface{}) error {
jsonData, err := json.Marshal(resource)
if err != nil {
return err
}
req, err := http.NewRequestWithContext(ctx, http.MethodPost, url, bytes.NewReader(jsonData))
if err != nil {
return err
}
resp, err := c.do(req)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return handleErrorResponse(resp)
}
return nil
}
func isFunctionDisabled(msg string) bool {
return strings.Contains(msg, "is disabled")
}
func makeGetRequest[T any](c *Client, ctx context.Context, url string, result *T) error {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
if err != nil {
return err
}
resp, err := c.do(req)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
if resp.StatusCode == http.StatusNotFound {
return ErrNotFound
}
return handleErrorResponse(resp)
}
dec := json.NewDecoder(resp.Body)
if err := dec.Decode(result); err != nil {
return err
}
return nil
}
func makePutRequest[T any](c *Client, ctx context.Context, url string, body []byte, result *T) error {
req, err := http.NewRequestWithContext(ctx, http.MethodPut, url, bytes.NewReader(body))
if err != nil {
return err
}
resp, err := c.do(req)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusCreated {
return handleErrorResponse(resp)
}
dec := json.NewDecoder(resp.Body)
if err := dec.Decode(result); err != nil {
return err
}
return nil
}
func handleErrorResponse(resp *http.Response) error {
respData := &struct {
ErrMsg string `json:"error_msg"`
}{}
body, err := readBody(resp.Body)
if err != nil {
err = multierr.Append(err, fmt.Errorf("read body failed"))
return err
}
err = json.Unmarshal([]byte(body), respData)
if err != nil {
color.Red("unmarshal response failed:")
color.Red(body)
return err
}
errMsg := errors.New(respData.ErrMsg)
if isFunctionDisabled(errMsg.Error()) {
return errMsg
}
return multierr.Append(fmt.Errorf("unexpected status code %d", resp.StatusCode), errMsg)
}