-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathconfig.go
79 lines (67 loc) · 1.61 KB
/
config.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
package hx
import (
"context"
"io"
"net/http"
"net/url"
)
type Config struct {
URL *url.URL
Body io.Reader
HTTPClient *http.Client
QueryParams url.Values
RequestHandlers []RequestHandler
ResponseHandlers []ResponseHandler
Interceptors []Interceptor
}
var newRequest func(ctx context.Context, meth, url string, body io.Reader) (*http.Request, error)
func NewConfig() (*Config, error) {
cfg := &Config{URL: new(url.URL), HTTPClient: new(http.Client), QueryParams: url.Values{}}
err := cfg.Apply(DefaultOptions...)
if err != nil {
return nil, err
}
return cfg, nil
}
func (cfg *Config) Apply(opts ...Option) error {
for _, f := range opts {
err := f.ApplyOption(cfg)
if err != nil {
return err
}
}
return nil
}
func (cfg *Config) DoRequest(ctx context.Context, meth string) (*http.Response, error) {
if len(cfg.QueryParams) > 0 {
q, err := url.ParseQuery(cfg.URL.RawQuery)
if err != nil {
return nil, err
}
for k, values := range cfg.QueryParams {
for _, v := range values {
q.Add(k, v)
}
}
cfg.URL.RawQuery = q.Encode()
}
req, err := newRequest(ctx, meth, cfg.URL.String(), cfg.Body)
if err != nil {
return nil, err
}
f := combineInterceptors(cfg.Interceptors).Wrap(cfg.doRequest)
return f(cfg.HTTPClient, req)
}
func (cfg *Config) doRequest(cli *http.Client, req *http.Request) (resp *http.Response, err error) {
for _, h := range cfg.RequestHandlers {
req, err = h(req)
if err != nil {
return nil, err
}
}
resp, err = cli.Do(req)
for _, h := range cfg.ResponseHandlers {
resp, err = h(resp, err)
}
return resp, err
}