-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient.go
247 lines (212 loc) · 5.88 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
/*
Copyright AppsCode Inc. and Contributors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package client
import (
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"strings"
)
var jsonHeader = http.Header{"Content-Type": []string{"application/json;charset=UTF-8"}}
// Version return the library version
func Version() string {
return "v0.0.1"
}
// Client represents a ByteBuilders api client
type Client struct {
url string
accessToken string
client *http.Client
org string
username string
password string
cookies []http.Cookie
}
// NewClient initializes and returns a API client.
func NewClient(baseURL ...string) *Client {
url := "https://byte.builders"
if len(baseURL) > 0 {
url = baseURL[0]
}
return &Client{
url: strings.TrimSuffix(url, "/"),
client: &http.Client{},
}
}
func (c *Client) WithAccessToken(accessToken string) *Client {
c.accessToken = accessToken
return c
}
func (c *Client) WithBasicAuth(username, password string) *Client {
c.username = username
c.password = password
return c
}
func (c *Client) WithCookies(cookies []http.Cookie) *Client {
c.cookies = cookies
return c
}
func (c *Client) WithOrganization(org string) *Client {
c.org = org
return c
}
// NewClientWithHTTP creates an API client with a custom http client
func NewClientWithHTTP(httpClient *http.Client, baseURL ...string) *Client {
client := NewClient(baseURL...)
client.client = httpClient
return client
}
// SetHTTPClient replaces default http.Client with user given one.
func (c *Client) SetHTTPClient(client *http.Client) {
c.client = client
}
func (c *Client) doRequest(method, path string, header http.Header, body io.Reader) (*http.Response, error) {
path = strings.TrimPrefix(path, "/")
req, err := http.NewRequest(method, c.url+"/api/v1/"+path, body)
if err != nil {
return nil, err
}
if len(c.accessToken) != 0 {
req.Header.Set("Authorization", "token "+c.accessToken)
}
if c.username != "" && c.password != "" {
req.SetBasicAuth(c.username, c.password)
}
if c.cookies != nil {
c.addCookies(req)
}
for k, v := range header {
req.Header[k] = v
}
return c.client.Do(req)
}
func (c *Client) addCookies(req *http.Request) {
var csrfToken string
for i := range c.cookies {
if c.cookies[i].Name == "_csrf" {
csrfToken = c.cookies[i].Value
}
req.AddCookie(&c.cookies[i])
}
req.Header.Set("X-Csrf-Token", csrfToken)
}
var (
ErrUnAuthorized = errors.New("401 Unauthorized")
ErrForbidden = errors.New("403 Forbidden")
ErrNotFound = errors.New("404 Not Found")
ErrStatusConflict = errors.New("409 Conflict")
)
func (c *Client) getResponse(method, path string, header http.Header, body io.Reader) ([]byte, error) {
resp, err := c.doRequest(method, path, header, body)
if err != nil {
return nil, err
}
defer resp.Body.Close()
data, err := io.ReadAll(resp.Body)
if err != nil {
return nil, err
}
if err := parseStatusCode(resp.StatusCode, data); err != nil {
return nil, err
}
return data, nil
}
func (c *Client) getParsedResponse(method, path string, header http.Header, body io.Reader, obj interface{}) error {
data, err := c.getResponse(method, path, header, body)
if err != nil {
return err
}
return json.Unmarshal(data, obj)
}
func (c *Client) getResponseWithCookies(method, path string, header http.Header, body io.Reader) ([]byte, []http.Cookie, error) {
resp, err := c.doRequest(method, path, header, body)
if err != nil {
return nil, nil, err
}
defer resp.Body.Close()
data, err := io.ReadAll(resp.Body)
if err != nil {
return nil, nil, err
}
if err := parseStatusCode(resp.StatusCode, data); err != nil {
return nil, nil, err
}
var cookies []http.Cookie
for _, c := range resp.Cookies() {
cookie := *c
cookies = append(cookies, cookie)
}
return data, cookies, nil
}
func (c *Client) getStatusCode(method, path string, header http.Header, body io.Reader) (int, error) {
resp, err := c.doRequest(method, path, header, body)
if err != nil {
return -1, err
}
defer resp.Body.Close()
return resp.StatusCode, nil
}
func parseStatusCode(statusCode int, data []byte) error {
switch statusCode {
case http.StatusUnauthorized:
return ErrUnAuthorized
case http.StatusForbidden:
return ErrForbidden
case http.StatusNotFound:
return ErrNotFound
case http.StatusConflict:
return ErrStatusConflict
case http.StatusUnprocessableEntity:
return fmt.Errorf("422 Unprocessable Entity: %s", string(data))
}
if statusCode/100 != 2 {
errMap := make(map[string]interface{})
if err := json.Unmarshal(data, &errMap); err != nil {
// when the JSON can't be parsed, data was probably empty or a plain string,
// so we try to return a helpful error anyway
return fmt.Errorf("Unknown API Error: %d %s", statusCode, string(data))
}
return errors.New(errMap["message"].(string))
}
return nil
}
func (c *Client) getOrganization() (string, error) {
org := c.org
if org == "" {
user, err := c.GetCurrentUser()
if err != nil {
return "", fmt.Errorf("organization name wasn't provided. Automatic user detection failed with error: %w", err)
}
org = user.UserName
}
return org, nil
}
type queryParams struct {
key string
value string
}
func setQueryParams(apiPath string, params []queryParams) (string, error) {
u, err := url.Parse(apiPath)
if err != nil {
return "", err
}
q := u.Query()
for i := range params {
q.Set(params[i].key, params[i].value)
}
u.RawQuery = q.Encode()
return u.String(), nil
}