forked from lucperkins/rek
-
Notifications
You must be signed in to change notification settings - Fork 0
/
options.go
291 lines (242 loc) · 5.92 KB
/
options.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
package rek
import (
"bytes"
"context"
"encoding/gob"
"encoding/json"
"fmt"
"io"
"net/http"
"time"
"golang.org/x/oauth2"
)
type options struct {
headers map[string]string
timeout time.Duration
username string
password string
data interface{}
userAgent string
jsonObj interface{}
callback func(*Response)
cookies []*http.Cookie
file *file
formData map[string]string
cookieJar *http.CookieJar
bearer string
disallowRedirects bool
accept string
reqModifier func(*http.Request)
apiKey string
ctx context.Context
client *http.Client
oauth2Cfg *oauth2Config
}
type oauth2Config struct {
config *oauth2.Config
token *oauth2.Token
}
func (o *options) validate() error {
i := 0
if o.jsonObj != nil {
i++
}
if o.data != nil {
i++
}
if o.formData != nil {
i++
}
// Throw an error if the request body has been set more than once.
if i > 1 {
return ErrRequestBodySetMultipleTimes
}
return nil
}
type Option func(*options)
// Add headers to the request.
func Headers(headers map[string]string) Option {
return func(opts *options) {
opts.headers = headers
}
}
// Add a timeout to the request.
func Timeout(timeout time.Duration) Option {
return func(opts *options) {
opts.timeout = timeout
}
}
// Add a basic auth username and password to the request.
func BasicAuth(username, password string) Option {
return func(opts *options) {
opts.username = username
opts.password = password
}
}
// Add any interface{} that can be serialized to a []byte and apply a "Content-Type: application/octet-stream" header.
func Data(data interface{}) Option {
return func(opts *options) {
opts.data = data
}
}
// Add a User-Agent header to the request.
func UserAgent(agent string) Option {
return func(opts *options) {
opts.userAgent = agent
}
}
// Add any interface{} that can be marshaled as JSON to the request body and apply a "Content-Type:
// application/json;charset=utf-8" header.
func Json(v interface{}) Option {
return func(opts *options) {
opts.jsonObj = v
}
}
// Add a callback function for handling the Response.
func Callback(cb func(*Response)) Option {
return func(opts *options) {
opts.callback = cb
}
}
// Add cookies to the request.
func Cookies(cookies []*http.Cookie) Option {
return func(opts *options) {
opts.cookies = cookies
}
}
// Add a cookie jar to the request.
func CookieJar(jar http.CookieJar) Option {
return func(opts *options) {
opts.cookieJar = &jar
}
}
// Create a multipart file upload request.
func File(fieldName, filepath string, params map[string]string) Option {
return func(opts *options) {
opts.file = &file{
FieldName: fieldName,
Filepath: filepath,
Params: params,
}
}
}
// Add key/value form data to the request body and apply a "Content-Type: application/x-www-form-urlencoded" header.
func FormData(form map[string]string) Option {
return func(opts *options) {
opts.formData = form
}
}
// Add a bearer header of the form "Authorization: Bearer ..."
func Bearer(bearer string) Option {
return func(opts *options) {
opts.bearer = bearer
}
}
// Turn redirects off.
func DisallowRedirects() Option {
return func(opts *options) {
opts.disallowRedirects = true
}
}
// Applies an Accept header to the request.
func Accept(accept string) Option {
return func(opts *options) {
opts.accept = accept
}
}
// Applies a user-provided request modification function. Applied after all other request modifications have been
// made by the selected options.
func RequestModifier(modifier func(*http.Request)) Option {
return func(opts *options) {
opts.reqModifier = modifier
}
}
// Adds an API key to the request.
func ApiKey(key string) Option {
return func(opts *options) {
opts.apiKey = key
}
}
// Pass a context into the HTTP request (allows for request cancellation, for example).
func Context(ctx context.Context) Option {
return func(opts *options) {
opts.ctx = ctx
}
}
// Provide your own http.Client struct to make the request.
func Client(client *http.Client) Option {
return func(opts *options) {
opts.client = client
}
}
// Apply an OAuth2 configuration and token to the request.
func OAuth2(cfg *oauth2.Config, tok *oauth2.Token) Option {
return func(opts *options) {
opts.oauth2Cfg = &oauth2Config{
config: cfg,
token: tok,
}
}
}
func buildOptions(opts ...Option) (*options, error) {
os := &options{}
for _, opt := range opts {
opt(os)
}
if err := os.validate(); err != nil {
return nil, err
}
return os, nil
}
func setHeaders(req *http.Request, opts *options) *http.Request {
if opts.headers != nil {
for k, v := range opts.headers {
req.Header.Set(k, v)
}
}
if opts.userAgent != "" {
req.Header.Set("User-Agent", opts.userAgent)
}
if opts.jsonObj != nil {
req.Header.Set("Content-Type", "application/json; charset=utf-8")
}
if opts.data != nil {
req.Header.Set("Content-Type", "application/octet-stream")
}
if opts.formData != nil {
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
}
if opts.accept != "" {
req.Header.Set("Accept", opts.accept)
}
if opts.apiKey != "" {
req.Header.Set("Authorization", fmt.Sprintf("Basic %s", opts.apiKey))
}
return req
}
func setBasicAuth(req *http.Request, opts *options) {
if opts.username != "" && opts.password != "" {
req.SetBasicAuth(opts.username, opts.password)
}
}
func setCookies(req *http.Request, opts *options) {
if opts.cookies != nil {
for _, c := range opts.cookies {
req.AddCookie(c)
}
}
}
func getData(opts *options) (io.Reader, error) {
var buf bytes.Buffer
if err := gob.NewEncoder(&buf).Encode(opts.data); err != nil {
return nil, err
}
return &buf, nil
}
func getJson(opts *options) (io.Reader, error) {
js, err := json.Marshal(opts.jsonObj)
if err != nil {
return nil, err
}
return bytes.NewBuffer(js), nil
}