-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathclient.go
96 lines (78 loc) · 2.18 KB
/
client.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
package hx
import (
"context"
"io"
"io/ioutil"
"net/http"
)
func Get(ctx context.Context, url string, opts ...Option) error {
return NewClient().Get(ctx, url, opts...)
}
func Post(ctx context.Context, url string, opts ...Option) error {
return NewClient().Post(ctx, url, opts...)
}
func Put(ctx context.Context, url string, opts ...Option) error {
return NewClient().Put(ctx, url, opts...)
}
func Patch(ctx context.Context, url string, opts ...Option) error {
return NewClient().Patch(ctx, url, opts...)
}
func Delete(ctx context.Context, url string, opts ...Option) error {
return NewClient().Delete(ctx, url, opts...)
}
type Client struct {
opts []Option
}
// NewClient creates a new http client instance.
func NewClient(opts ...Option) *Client {
return &Client{
opts: opts,
}
}
func (c *Client) Get(ctx context.Context, url string, opts ...Option) error {
return c.request(ctx, http.MethodGet, url, opts...)
}
func (c *Client) Post(ctx context.Context, url string, opts ...Option) error {
return c.request(ctx, http.MethodPost, url, opts...)
}
func (c *Client) Put(ctx context.Context, url string, opts ...Option) error {
return c.request(ctx, http.MethodPut, url, opts...)
}
func (c *Client) Patch(ctx context.Context, url string, opts ...Option) error {
return c.request(ctx, http.MethodPatch, url, opts...)
}
func (c *Client) Delete(ctx context.Context, url string, opts ...Option) error {
return c.request(ctx, http.MethodDelete, url, opts...)
}
// With clones the current client and applies the given options.
func (c *Client) With(opts ...Option) *Client {
newOpts := make([]Option, 0, len(c.opts)+len(opts))
newOpts = append(newOpts, c.opts...)
newOpts = append(newOpts, opts...)
return NewClient(newOpts...)
}
func (c *Client) request(ctx context.Context, meth string, url string, opts ...Option) error {
cfg, err := NewConfig()
if err != nil {
return err
}
err = cfg.Apply(c.opts...)
if err != nil {
return err
}
err = cfg.Apply(URL(url))
if err != nil {
return err
}
err = cfg.Apply(opts...)
if err != nil {
return err
}
resp, err := cfg.DoRequest(ctx, meth)
if err != nil {
return err
}
io.Copy(ioutil.Discard, resp.Body)
resp.Body.Close()
return nil
}