forked from bearded-web/bearded
/
client.go
417 lines (367 loc) · 10.6 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
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
package client
// Client package inspired by google github client https://github.com/google/go-github
import (
"bytes"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"mime/multipart"
"net/http"
"net/url"
"reflect"
"github.com/Sirupsen/logrus"
"github.com/facebookgo/stackerr"
"github.com/google/go-querystring/query"
"golang.org/x/net/context"
"gopkg.in/mgo.v2/bson"
)
const (
libraryVersion = "0.1"
userAgent = "go-bearded-client/" + libraryVersion
defaultBaseURL = "http://127.0.0.1:3003/api/"
mediaTypeV1 = "application/json"
apiVersion = 1
)
// A Client manages communication with the Bearded API.
type Client struct {
// HTTP client used to communicate with the API.
client *http.Client
// Base URL for API requests. BaseURL should
// always be specified with a trailing slash.
BaseURL *url.URL
// User agent used when communicating with the Bearded API.
UserAgent string
// Token sent in header to authenticate
Token string
// Show different debug information
Debug bool
// Services used for talking to different parts of the Bearded API.
Plugins *PluginsService
Plans *PlansService
Agents *AgentsService
Scans *ScansService
Files *FilesService
Tokens *TokensService
}
// NewClient returns a new Bearded API client. If a nil httpClient is
// provided, http.DefaultClient will be used. To use API methods which require
// authentication, provide an http.Client that will perform the authentication
// for you (such as that provided by the goauth2 library).
func NewClient(baseUrl string, httpClient *http.Client) *Client {
if httpClient == nil {
httpClient = http.DefaultClient
}
if baseUrl == "" {
baseUrl = defaultBaseURL
}
baseURL, _ := url.Parse(baseUrl)
c := &Client{client: httpClient, BaseURL: baseURL, UserAgent: userAgent}
c.Plugins = &PluginsService{client: c}
c.Plans = &PlansService{client: c}
c.Agents = &AgentsService{client: c}
c.Scans = &ScansService{client: c}
c.Files = &FilesService{client: c}
c.Tokens = &TokensService{client: c}
return c
}
// addOptions adds the parameters in opt as URL query parameters to s. opt
// must be a struct whose fields may contain "url" tags.
func addOptions(s string, opt interface{}) (string, error) {
if opt == nil {
return s, nil
}
v := reflect.ValueOf(opt)
if v.Kind() == reflect.Ptr && v.IsNil() {
return s, nil
}
u, err := url.Parse(s)
if err != nil {
return s, err
}
qs, err := query.Values(opt)
if err != nil {
return s, err
}
u.RawQuery = qs.Encode()
return u.String(), nil
}
func (c *Client) SetBaseUrl(u string) error {
baseURL, err := url.Parse(u)
if err != nil {
return err
}
c.BaseURL = baseURL
return nil
}
// NewRequest creates an API request. A relative URL can be provided in urlStr,
// in which case it is resolved relative to the BaseURL of the Client.
// Relative URLs should always be specified without a preceding slash. If
// specified, the value pointed to by body is JSON encoded and included as the
// request body.
func (c *Client) NewRequest(method, urlStr string, body interface{}) (*http.Request, error) {
u, err := c.getUrl(urlStr)
if err != nil {
return nil, err
}
var buf io.Reader
if body != nil {
if bodyReader, casted := body.(io.Reader); casted {
buf = bodyReader
} else {
bufW := new(bytes.Buffer)
err := json.NewEncoder(bufW).Encode(body)
if err != nil {
return nil, err
}
buf = bufW
}
}
if c.Debug {
logrus.Debugf("%s %s", method, u)
}
req, err := http.NewRequest(method, u, buf)
if err != nil {
return nil, err
}
req.Header.Add("Accept", mediaTypeV1)
if c.UserAgent != "" {
req.Header.Add("User-Agent", c.UserAgent)
}
if req.Method == "POST" || req.Method == "PUT" || req.Method == "PATCH" {
req.Header.Add("Content-Type", "application/json")
}
if c.Token != "" {
req.Header.Add("Authorization", fmt.Sprintf("Bearer %s", c.Token))
}
return req, nil
}
func (c *Client) getUrl(urlStr string) (string, error) {
urlStr = fmt.Sprintf("v%d/%s", apiVersion, urlStr)
rel, err := url.Parse(urlStr)
if err != nil {
return "", err
}
u := c.BaseURL.ResolveReference(rel)
return u.String(), nil
}
// Do sends an API request and returns the API response. The API response is
// JSON decoded and stored in the value pointed to by v, or returned as an
// error if an API error has occurred. If v implements the io.Writer
// interface, the raw response body will be written to v, without attempting to
// first decode it.
func (c *Client) Do(ctx context.Context, req *http.Request, v interface{}) (*http.Response, error) {
var resp *http.Response
ret := make(chan error, 1)
go func() {
var err error
resp, err = c.client.Do(req)
ret <- err
}()
select {
case <-ctx.Done():
type canceler interface {
CancelRequest(*http.Request)
}
transport := c.client.Transport
if transport == nil {
// default transport is used
transport = http.DefaultTransport
}
tr, ok := transport.(canceler)
if !ok {
return nil, fmt.Errorf("client Transport of type %T doesn't support CancelRequest; Timeout not supported", transport)
}
tr.CancelRequest(req)
<-ret // Wait goroutine to return after cancellation.
return nil, stackerr.Wrap(ctx.Err())
case err := <-ret:
if err != nil {
return nil, err
}
}
defer resp.Body.Close()
err := CheckResponse(resp)
if err != nil {
// even though there was an error, we still return the response
// in case the caller wants to inspect it further
return resp, err
}
if v != nil {
if w, ok := v.(io.Writer); ok {
io.Copy(w, resp.Body)
} else {
err = json.NewDecoder(resp.Body).Decode(v)
}
}
return resp, err
}
// Helper method to get a list of payload objects
func (c *Client) List(ctx context.Context, url string, opts interface{}, payload interface{}) error {
u, err := addOptions(url, opts)
if err != nil {
return err
}
req, err := c.NewRequest("GET", u, nil)
if err != nil {
return err
}
_, err = c.Do(ctx, req, payload)
return err
}
// Helper method to get a resource by id
func (c *Client) Get(ctx context.Context, url string, id string, payload interface{}) error {
url = fmt.Sprintf("%s/%s", url, id)
req, err := c.NewRequest("GET", url, nil)
if err != nil {
return err
}
_, err = c.Do(ctx, req, payload)
return err
}
func (c *Client) Create(ctx context.Context, url string, send interface{}, payload interface{}) error {
req, err := c.NewRequest("POST", url, send)
if err != nil {
return err
}
_, err = c.Do(ctx, req, payload)
return err
}
func (c *Client) Update(ctx context.Context, url string, id string, send interface{}, payload interface{}) error {
url = fmt.Sprintf("%s/%s", url, id)
req, err := c.NewRequest("PUT", url, send)
if err != nil {
return err
}
_, err = c.Do(ctx, req, payload)
return err
}
func (c *Client) Delete(ctx context.Context, url string, id string) error {
url = fmt.Sprintf("%s/%s", url, id)
req, err := c.NewRequest("DELETE", url, nil)
if err != nil {
return err
}
_, err = c.Do(ctx, req, nil)
return err
}
func (c *Client) Upload(ctx context.Context, urlStr string, files []*UploadedFile, payload interface{}) error {
var b bytes.Buffer
w := multipart.NewWriter(&b)
for _, ufile := range files {
dst, err := w.CreateFormFile(ufile.Fieldname, ufile.Filename)
if err != nil {
return err
}
if _, err = io.Copy(dst, ufile.Data); err != nil {
return err
}
}
if err := w.Close(); err != nil {
return err
}
req, err := c.NewRequest("POST", urlStr, &b)
if err != nil {
return err
}
req.Header.Set("Content-Type", w.FormDataContentType())
_, err = c.Do(ctx, req, payload)
return err
}
// convert string id to ObjectId
func ToId(id string) bson.ObjectId {
return bson.ObjectIdHex(id)
}
// convert ObjectId to string
func FromId(id bson.ObjectId) string {
return id.Hex()
}
// CheckResponse checks the API response for errors, and returns them if
// present. A response is considered an error if it has a status code outside
// the 200 range. API error responses are expected to have either no response
// body, or a JSON response body that maps to ErrorResponse. Any other
// response body will be silently ignored.
func CheckResponse(r *http.Response) error {
if c := r.StatusCode; 200 <= c && c <= 299 {
return nil
}
errorResponse := &ErrorResponse{Response: r}
data, err := ioutil.ReadAll(r.Body)
if err == nil && data != nil {
serviceError := &ServiceError{}
if err := json.Unmarshal(data, serviceError); err == nil {
errorResponse.ServiceError = serviceError
}
}
return errorResponse
}
type ErrorResponse struct {
Response *http.Response
ServiceError *ServiceError
}
func (r *ErrorResponse) Error() string {
msg := "ErrorResponse: "
if r.Response != nil {
msg = fmt.Sprintf("%v %v: %d",
r.Response.Request.Method,
r.Response.Request.URL,
r.Response.StatusCode)
}
if r.ServiceError != nil {
msg = fmt.Sprintf("%s %s", msg, r.ServiceError)
}
return msg
}
// ServiceError is a transport object to pass information about a non-Http error occurred in a WebService while processing a request.
type ServiceError struct {
Code int
Message string
}
// NewError returns a ServiceError using the code and reason
func NewError(code int, message string) ServiceError {
return ServiceError{Code: code, Message: message}
}
// Error returns a text representation of the service error
func (s ServiceError) Error() string {
return fmt.Sprintf("[ServiceError:%v] %v", s.Code, s.Message)
}
// parseBoolResponse determines the boolean result from a Bearded API response.
// Several Bearded API methods return boolean responses indicated by the HTTP
// status code in the response (true indicated by a 204, false indicated by a
// 404). This helper function will determine that result and hide the 404
// error if present. Any other error will be returned through as-is.
func parseBoolResponse(err error) (bool, error) {
if err == nil {
return true, nil
}
if err, ok := err.(*ErrorResponse); ok && err.Response.StatusCode == http.StatusNotFound {
// Simply false. In this one case, we do not pass the error through.
return false, nil
}
// some other real error occurred
return false, err
}
// return true if http status code is 404 (Status not found)
func IsNotFound(err error) bool {
if err == nil {
return false
}
if err, ok := err.(*ErrorResponse); ok && err.Response.StatusCode == http.StatusNotFound {
return true
}
return false
}
// return true if http status code is 409 (Status conflict)
func IsConflicted(err error) bool {
if err == nil {
return false
}
if err, ok := err.(*ErrorResponse); ok && err.Response.StatusCode == http.StatusConflict {
return true
}
return false
}
type UploadedFile struct {
Fieldname, Filename string
Data io.Reader
}