-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathoptions.go
More file actions
63 lines (51 loc) · 1.29 KB
/
Copy pathoptions.go
File metadata and controls
63 lines (51 loc) · 1.29 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
package patch
import (
"fmt"
"net/http"
"time"
)
// DefaultTimeout is the default time limit for requests made by the client.
const DefaultTimeout = 30 * time.Second
var DefaultResponseInterceptor = StatusValidatorInterceptor(Accept2xx)
type Option func(c *Client)
func WithBaseURL(url string) Option {
return func(c *Client) {
c.BaseURL = url
}
}
func WithTimeout(d time.Duration) Option {
return func(c *Client) {
switch bc := c.BaseClient.(type) {
case *http.Client:
bc.Timeout = d
return
}
panic(fmt.Errorf("cannot set timeout on base client of type %T", c))
}
}
func WithEncoder(enc Encoder) Option {
return func(c *Client) {
c.DefaultEncoder = enc
}
}
func WithRequestInterceptor(f func(*http.Request) (*http.Request, error)) Option {
return func(c *Client) {
c.RequestInterceptor = f
}
}
func WithResponseInterceptor(f func(*http.Response) (*http.Response, error)) Option {
return func(c *Client) {
c.ResponseInterceptor = f
}
}
func StatusValidatorInterceptor(f func(status int) bool) func(*http.Response) (*http.Response, error) {
return func(rsp *http.Response) (*http.Response, error) {
if !f(rsp.StatusCode) {
return rsp, BadStatusError(rsp.StatusCode)
}
return rsp, nil
}
}
var Accept2xx = func(status int) bool {
return status >= 200 && status < 300
}