-
Notifications
You must be signed in to change notification settings - Fork 0
/
request.go
295 lines (247 loc) · 7 KB
/
request.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
package httpr
import (
"context"
"errors"
"fmt"
"net/http"
"net/url"
"strings"
)
// RequestBuilder struct provides convenient interface
// for *http.Request instances construction.
type RequestBuilder struct {
err error
ctx context.Context
url *url.URL
method string
body any
headers map[string][]string
queryParams url.Values
cookies []*http.Cookie
basicAuthCredentials *struct {
user string
pass string
}
}
// NewRequest creates new RequestBuilder instance, which used for
// http.Request building.
func NewRequest() *RequestBuilder {
return &RequestBuilder{
headers: make(map[string][]string),
queryParams: make(url.Values),
}
}
// SetURL sets target URL for current request.
func (rb *RequestBuilder) SetURL(requestURL string) *RequestBuilder {
rb.url, rb.err = parseURL(requestURL)
return rb
}
// SetMethod sets method for current request.
func (rb *RequestBuilder) SetMethod(method string) *RequestBuilder {
rb.method = method
return rb
}
// Get method create "get" HTTP request with specified body.
func (rb *RequestBuilder) Get(requestURL string, body any) *RequestBuilder {
rb.method = http.MethodGet
rb.SetURL(requestURL)
rb.body = body
return rb
}
// Post method create "post" HTTP request with specified body.
func (rb *RequestBuilder) Post(requestURL string, body any) *RequestBuilder {
rb.method = http.MethodPost
rb.SetURL(requestURL)
rb.body = body
return rb
}
// Patch method create "patch" HTTP request with specified body.
func (rb *RequestBuilder) Patch(requestURL string, body any) *RequestBuilder {
rb.method = http.MethodPatch
rb.SetURL(requestURL)
rb.body = body
return rb
}
// Put method create "put" HTTP request with specified body.
func (rb *RequestBuilder) Put(requestURL string, body any) *RequestBuilder {
rb.method = http.MethodPut
rb.SetURL(requestURL)
rb.body = body
return rb
}
// Options method create "options" HTTP request with specified body.
func (rb *RequestBuilder) Options(requestURL string, body any) *RequestBuilder {
rb.method = http.MethodOptions
rb.SetURL(requestURL)
rb.body = body
return rb
}
// Head method create "head" HTTP request.
func (rb *RequestBuilder) Head(requestURL string) *RequestBuilder {
rb.method = http.MethodHead
rb.SetURL(requestURL)
return rb
}
// Connect method create "connect" HTTP request.
func (rb *RequestBuilder) Connect(requestURL string) *RequestBuilder {
rb.method = http.MethodConnect
rb.SetURL(requestURL)
return rb
}
// Delete method create "delete" HTTP request with specified body.
func (rb *RequestBuilder) Delete(requestURL string, body any) *RequestBuilder {
rb.method = http.MethodDelete
rb.SetURL(requestURL)
rb.body = body
return rb
}
// Trace method create "trace" HTTP request.
func (rb *RequestBuilder) Trace(requestURL string) *RequestBuilder {
rb.method = http.MethodTrace
rb.SetURL(requestURL)
return rb
}
// SetBody method sets body for current request.
// Body can be one of following concrete types or types, which implement
// interfaces: string, []byte, io.Reader.
func (rb *RequestBuilder) SetBody(body any) *RequestBuilder {
rb.body = body
return rb
}
// SetContext sets context for current request. If provided context is nil,
// new one will be created with context.Background().
func (rb *RequestBuilder) SetContext(ctx context.Context) *RequestBuilder {
rb.ctx = ctx
return rb
}
// SetHeader sets header with provided key and value.
func (rb *RequestBuilder) SetHeader(key, value string) *RequestBuilder {
if rb.headers == nil {
rb.headers = make(map[string][]string)
}
rb.headers[key] = append(rb.headers[key], value)
return rb
}
// SetHeaders creates and sets headers for each key/value pair in provided map.
func (rb *RequestBuilder) SetHeaders(headers map[string]string) *RequestBuilder {
for key, value := range headers {
rb.SetHeader(key, value)
}
return rb
}
// SetQueryString provides option to set query string parameters by passing
// raw string.
func (rb *RequestBuilder) SetQueryString(query string) *RequestBuilder {
if rb.queryParams == nil {
rb.queryParams = make(url.Values)
}
queryParams, err := url.ParseQuery(query)
if err != nil {
rb.err = fmt.Errorf("malformed query: %w", err)
return rb
}
for key, values := range queryParams {
for _, value := range values {
rb.queryParams.Add(key, value)
}
}
return rb
}
// SetQueryParam sets query parameter with following key and value.
func (rb *RequestBuilder) SetQueryParam(key, value string) *RequestBuilder {
if strings.TrimSpace(key) == "" {
return rb
}
if rb.queryParams == nil {
rb.queryParams = make(url.Values)
}
rb.queryParams.Set(key, value)
return rb
}
// SetQueryParams sets multiple query parameters by calling SetQueryParams for each
// key/value in map.
func (rb *RequestBuilder) SetQueryParams(params map[string]string) *RequestBuilder {
if rb.queryParams == nil {
rb.queryParams = make(url.Values, len(params))
}
for key, value := range params {
rb.SetQueryParam(key, value)
}
return rb
}
// SetCookies sets cookies for current request.
func (rb *RequestBuilder) SetCookies(cookies []*http.Cookie) *RequestBuilder {
rb.cookies = cookies
return rb
}
// SetBasicAuth encodes and sets basic HTTP authentication credentials.
func (rb *RequestBuilder) SetBasicAuth(user, pass string) *RequestBuilder {
rb.basicAuthCredentials = &struct {
user string
pass string
}{
user: user,
pass: pass,
}
return rb
}
// Build composes *http.Request instance. If errors occurred during previous building steps,
// they will be returned.
func (rb *RequestBuilder) Build() (*http.Request, error) {
if rb.err != nil {
return nil, rb.err
}
if rb.url == nil {
return nil, errors.New("request url is not set")
}
reqURL := composeURL(rb.url, rb.queryParams)
reqBody, err := convertBodyToReader(rb.body)
if err != nil {
return nil, fmt.Errorf("failed to build request body: %w", err)
}
reqMethod := composeMethod(rb.method)
reqCtx := rb.ctx
if reqCtx == nil {
reqCtx = context.Background()
}
req, err := http.NewRequestWithContext(reqCtx, reqMethod, reqURL, reqBody)
if err != nil {
return nil, err
}
if rb.basicAuthCredentials != nil {
req.SetBasicAuth(rb.basicAuthCredentials.user, rb.basicAuthCredentials.pass)
}
for key, values := range rb.headers {
for _, value := range values {
req.Header.Add(key, value)
}
}
for _, cookie := range rb.cookies {
req.AddCookie(cookie)
}
return req, nil
}
func composeURL(reqURL *url.URL, params url.Values) string {
encodedQuery := params.Encode()
if encodedQuery == "" {
return reqURL.String()
}
if reqURL.RawQuery == "" {
reqURL.RawQuery = encodedQuery
} else {
reqURL.RawQuery += "&" + encodedQuery
}
return reqURL.String()
}
func composeMethod(method string) string {
if method == "" {
return http.MethodGet
}
return strings.ToUpper(method)
}
func parseURL(requestURL string) (*url.URL, error) {
if !IsValidURL(requestURL) {
return nil, fmt.Errorf("invalid URL '%s'", requestURL)
}
return url.Parse(requestURL)
}