forked from mistermoe/httpr
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathoptions.go
More file actions
273 lines (217 loc) · 5.94 KB
/
Copy pathoptions.go
File metadata and controls
273 lines (217 loc) · 5.94 KB
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
package httpr
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"strings"
"time"
"github.com/alecthomas/types/optional"
)
type ClientOption interface {
Client(*Client)
}
type RequestOption interface {
Request(*requestOptions)
}
type Option interface {
ClientOption
RequestOption
}
type requestOptions struct {
requestBody optional.Option[requestBodyHandler]
responseBody optional.Option[responseBodyHandler]
queryParams optional.Option[url.Values]
headers map[string]string
interceptors []Interceptor
}
type baseURLOption string
func (b baseURLOption) Client(c *Client) {
c.baseURL = optional.Some(string(b))
}
func BaseURL(baseURL string) ClientOption {
return baseURLOption(baseURL)
}
type httpClientOption http.Client
func (h httpClientOption) Client(c *Client) {
httpClient := http.Client(h)
c.httpClient = &httpClient
}
func HTTPClient(h http.Client) ClientOption {
return httpClientOption(h)
}
type headerOption struct {
key, value string
}
func (h headerOption) Client(c *Client) {
if c.headers == nil {
c.headers = make(map[string]string)
}
c.headers[h.key] = h.value
}
func (h headerOption) Request(r *requestOptions) {
if r.headers == nil {
r.headers = make(map[string]string)
}
r.headers[h.key] = h.value
}
// Header creates a new Option for setting headers.
func Header(key, value string) Option {
return headerOption{key, value}
}
type queryParamOption struct {
key, value string
}
func (q queryParamOption) Request(r *requestOptions) {
queryParams, ok := r.queryParams.Get()
if ok {
queryParams.Add(q.key, q.value)
} else {
queryParams = url.Values{}
queryParams.Add(q.key, q.value)
r.queryParams = optional.Some(queryParams)
}
}
func QueryParam(key, value string) RequestOption {
return queryParamOption{key, value}
}
func Inspect() Option {
return Intercept(Inspector())
}
type timeoutOption time.Duration
func (t timeoutOption) Client(c *Client) {
if c.httpClient != nil {
c.httpClient.Timeout = time.Duration(t)
} else {
c.httpClient = &http.Client{
Timeout: time.Duration(t),
}
}
}
func Timeout(timeout time.Duration) ClientOption {
return timeoutOption(timeout)
}
type interceptOption struct {
Interceptor
}
func (i interceptOption) Client(c *Client) {
c.interceptors = append(c.interceptors, i.Interceptor)
}
func (i interceptOption) Request(r *requestOptions) {
r.interceptors = append(r.interceptors, i.Interceptor)
}
func Intercept(i Interceptor) Option {
return interceptOption{i}
}
type requestBodyHandler func() (io.Reader, string, error)
type requestBodyOption struct {
handler requestBodyHandler
}
func (r requestBodyOption) Request(opts *requestOptions) {
opts.requestBody = optional.Some(r.handler)
}
func (r requestBodyOption) Client(c *Client) {
c.requestBodyHandler = optional.Some(r.handler)
}
func RequestBody(contentType string, bodyFunc func() (io.Reader, error)) Option {
return requestBodyOption{
handler: func() (io.Reader, string, error) {
body, err := bodyFunc()
return body, contentType, err
},
}
}
// RequestBodyJSON json marshals whatever is passed in and sets the content type to application/json.
func RequestBodyJSON(body any) Option {
return RequestBody("application/json", func() (io.Reader, error) {
b, err := json.Marshal(body)
if err != nil {
return nil, err
}
return bytes.NewReader(b), nil
})
}
// RequestBodyString sets the content type to text/plain.
func RequestBodyString(body string) Option {
return RequestBody("text/plain", func() (io.Reader, error) {
return strings.NewReader(body), nil
})
}
// RequestBodyForm sets the content type to application/x-www-form-urlencoded.
func RequestBodyForm(data url.Values) Option {
return RequestBody("application/x-www-form-urlencoded", func() (io.Reader, error) {
return strings.NewReader(data.Encode()), nil
})
}
// RequestBodyBytes sets the content type to application/octet-stream.
func RequestBodyBytes(contentType string, body []byte) Option {
return RequestBody(contentType, func() (io.Reader, error) {
return bytes.NewReader(body), nil
})
}
// RequestBodyStream sets the content type to the provided value. good for when you have a stream of data.
func RequestBodyStream(contentType string, body io.Reader) Option {
return RequestBody(contentType, func() (io.Reader, error) {
return body, nil
})
}
type responseBodyHandler func(resp *http.Response) error
type responseHandlerOption struct {
handler responseBodyHandler
}
func (r responseHandlerOption) Request(opts *requestOptions) {
opts.responseBody = optional.Some(r.handler)
}
func (r responseHandlerOption) Client(c *Client) {
c.responseBodyHandler = optional.Some(r.handler)
}
func ResponseBodyJSON(successBody any, errBody any) Option {
return responseHandlerOption{handler: func(resp *http.Response) error {
body, err := io.ReadAll(resp.Body)
if err != nil {
return fmt.Errorf("failed to read response body: %w", err)
}
defer resp.Body.Close()
var target any
if resp.StatusCode >= http.StatusBadRequest {
target = errBody
} else {
target = successBody
}
if target != nil {
if err := json.Unmarshal(body, target); err != nil {
return fmt.Errorf("failed to unmarshal %d response body: %w", resp.StatusCode, err)
}
}
return nil
}}
}
func ResponseBodyString(dest *string) Option {
handler := func(resp *http.Response) error {
body, err := io.ReadAll(resp.Body)
if err != nil {
return fmt.Errorf("failed to read response body: %w", err)
}
defer resp.Body.Close()
*dest = string(body)
return nil
}
return responseHandlerOption{handler: handler}
}
func ResponseBodyBytes(dest *[]byte) Option {
handler := func(resp *http.Response) error {
body, err := io.ReadAll(resp.Body)
if err != nil {
return fmt.Errorf("failed to read response body: %w", err)
}
defer resp.Body.Close()
*dest = body
return nil
}
return responseHandlerOption{handler: handler}
}
func ResponseBody(handler responseBodyHandler) Option {
return responseHandlerOption{handler: handler}
}