forked from lusis/go-rundeck
-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
333 lines (289 loc) · 6.91 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
package httpclient
import (
"fmt"
"io"
"io/ioutil"
"net/http"
"net/http/cookiejar"
"net/url"
"sync"
multierror "github.com/hashicorp/go-multierror"
"golang.org/x/net/publicsuffix"
)
// Response represents an http response
type Response struct {
Body []byte
Headers http.Header
Cookies []*http.Cookie
Status int
}
// Request represents an http request
type Request struct {
httpClient *http.Client
cookieJar *cookiejar.Jar
url string
method string
contentType string
accept string
queryParams map[string]string
body io.Reader
headers map[string]string
allowedStatusCodes []int
sync.RWMutex
}
// RequestOption is a type for functional options
type RequestOption func(*Request) error
func (cr *Request) setAllowedStatusCode(i int) {
cr.allowedStatusCodes = append(cr.allowedStatusCodes, i)
}
func (cr *Request) getAllowedStatusCodes() []int {
return cr.allowedStatusCodes
}
func (cr *Request) setHTTPClient(c *http.Client) {
cr.httpClient = c
}
// AddHeaders adds custom headers to the request
func AddHeaders(h ...map[string]string) RequestOption {
return func(r *Request) error {
for _, pair := range h {
for k, v := range pair {
r.headers[k] = v
}
}
return nil
}
}
// SetClient sets a custom http.Client to use for the request
func SetClient(client *http.Client) RequestOption {
return func(r *Request) error {
r.setHTTPClient(client)
return nil
}
}
// QueryParams sets the query params for a request
func QueryParams(m map[string]string) RequestOption {
return func(r *Request) error {
r.queryParams = m
return nil
}
}
// SetCookieJar sets the cookie jar to be used with requests
func SetCookieJar(jar *cookiejar.Jar) RequestOption {
return func(r *Request) error {
r.cookieJar = jar
return nil
}
}
// JSON sets a request to accept and respond with json
func JSON() RequestOption {
return func(r *Request) error {
r.accept = ContentTypeJSON
r.contentType = ContentTypeJSON
return nil
}
}
// ContentType allows setting the content-type for the request
func ContentType(ct string) RequestOption {
return func(r *Request) error {
r.contentType = ct
return nil
}
}
// Accept allows setting the Accept header individually
func Accept(ct string) RequestOption {
return func(r *Request) error {
r.accept = ct
return nil
}
}
// RequestXML sets a request to accept and respond with json
func RequestXML() RequestOption {
return func(r *Request) error {
r.accept = ContentTypeXML
r.contentType = ContentTypeXML
return nil
}
}
// ExpectStatus sets expected status codes from a response
func ExpectStatus(codes ...int) RequestOption {
return func(r *Request) error {
for _, code := range codes {
r.setAllowedStatusCode(code)
}
return nil
}
}
// WithBody provides the body to be used with the http request
func WithBody(reader io.Reader) RequestOption {
return func(r *Request) error {
r.body = reader
return nil
}
}
// New creates a ClientRequest
func New(opts ...RequestOption) (*Request, *http.Request, error) {
return newHTTPRequest(opts...)
}
func delete() RequestOption {
return func(r *Request) error {
r.method = http.MethodDelete
return nil
}
}
func get() RequestOption {
return func(r *Request) error {
r.method = http.MethodGet
return nil
}
}
func put() RequestOption {
return func(r *Request) error {
r.method = http.MethodPut
return nil
}
}
func post() RequestOption {
return func(r *Request) error {
r.method = http.MethodPost
return nil
}
}
func head() RequestOption {
return func(r *Request) error {
r.method = http.MethodHead
return nil
}
}
func setURL(u string) RequestOption {
return func(r *Request) error {
r.url = u
return nil
}
}
// newHTTPRequest returns a new `Request` configured with various options
func newHTTPRequest(opts ...RequestOption) (*Request, *http.Request, error) {
r := &Request{}
if r.httpClient == nil {
r.setHTTPClient(&http.Client{})
}
codes := make([]int, 0)
headers := make(map[string]string)
r.allowedStatusCodes = codes
r.headers = headers
jar, jarErr := cookiejar.New(&cookiejar.Options{
PublicSuffixList: publicsuffix.List,
})
if jarErr != nil {
return nil, nil, jarErr
}
r.cookieJar = jar
for _, opt := range opts {
r.Lock()
if err := opt(r); err != nil {
r.Unlock()
return nil, nil, err
}
r.Unlock()
}
req, err := r.httpRequest()
return r, req, err
}
func (cr *Request) httpRequest() (*http.Request, error) {
if cr.accept == "" {
cr.accept = DefaultAccept
}
u, uErr := url.Parse(cr.url)
if uErr != nil {
return nil, uErr
}
if len(cr.queryParams) > 0 {
qs := url.Values{}
for q, p := range cr.queryParams {
qs.Add(q, p)
}
u.RawQuery = qs.Encode()
}
req, reqErr := http.NewRequest(cr.method, u.String(), cr.body)
if reqErr != nil {
return nil, reqErr
}
for k, v := range cr.headers {
req.Header.Add(k, v)
}
if cr.contentType != "" {
req.Header.Add("Content-Type", cr.contentType)
}
req.Header.Add("Accept", cr.accept)
return req, nil
}
// Get performs an http GET
func Get(url string, opts ...RequestOption) (*Response, error) {
doOpts := []RequestOption{
get(),
setURL(url),
}
doOpts = append(doOpts, opts...)
return doRequest(doOpts...)
}
// Delete performs an http DELETE
func Delete(url string, opts ...RequestOption) (*Response, error) {
opts = append(opts, delete())
opts = append(opts, setURL(url))
return doRequest(opts...)
}
// Post performs an http POST
func Post(url string, opts ...RequestOption) (*Response, error) {
opts = append(opts, post())
opts = append(opts, setURL(url))
return doRequest(opts...)
}
// Put performs an http PUT
func Put(url string, opts ...RequestOption) (*Response, error) {
doOpts := []RequestOption{
put(),
setURL(url),
}
doOpts = append(doOpts, opts...)
//opts = append(opts, put())
//opts = append(opts, setURL(url))
return doRequest(doOpts...)
}
// Head performs an http HEAD
func Head(url string, opts ...RequestOption) (*Response, error) {
opts = append(opts, head())
opts = append(opts, setURL(url))
return doRequest(opts...)
}
func doRequest(opts ...RequestOption) (*Response, error) {
response := &Response{}
cr, req, reqErr := newHTTPRequest(opts...)
if reqErr != nil {
return nil, reqErr
}
cr.httpClient.Jar = cr.cookieJar
resp, respErr := cr.httpClient.Do(req)
if respErr != nil {
return nil, respErr
}
readBody, readErr := ioutil.ReadAll(resp.Body)
if readErr != nil {
return nil, readErr
}
response.Body = readBody
response.Headers = resp.Header
response.Status = resp.StatusCode
response.Cookies = append(response.Cookies, resp.Cookies()...)
if len(cr.getAllowedStatusCodes()) != 0 {
passed := false
for _, code := range cr.getAllowedStatusCodes() {
if resp.StatusCode == code {
passed = true
break
}
}
if !passed {
return response, multierror.Append(ErrInvalidStatusCode, fmt.Errorf("status code %d", response.Status))
}
}
return response, nil
}