-
Notifications
You must be signed in to change notification settings - Fork 1
/
client.go
96 lines (80 loc) · 2.08 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 httpc
import (
"net/http"
"strings"
)
// Doer is an abstraction around a http client.
type Doer interface {
Do(*http.Request) (*http.Response, error)
}
// Client is the httpc client. The client sets the default backoff and encode func
// on the request that are created when making an http call. Those defaults can be
// overridden in the request builder.
type Client struct {
baseURL string
doer Doer
headers []kvPair
authFn AuthFn
encodeFn EncodeFn
backoff BackoffOptFn
}
// New returns a new client.
func New(doer Doer, opts ...ClientOptFn) *Client {
c := Client{
doer: doer,
encodeFn: JSONEncode(),
backoff: NewStopBackoff(),
}
for _, o := range opts {
c = o(c)
}
return &c
}
// Connect makes a connect http request.
func (c *Client) Connect(addr string) *Request {
return c.Req(http.MethodConnect, addr)
}
// Delete makes a delete http request.
func (c *Client) Delete(addr string) *Request {
return c.Req(http.MethodDelete, addr)
}
// Get makes a get http request.
func (c *Client) Get(addr string) *Request {
return c.Req(http.MethodGet, addr)
}
// HEAD makes a head http request.
func (c *Client) Head(addr string) *Request {
return c.Req(http.MethodHead, addr)
}
// Options makes a options http request.
func (c *Client) Options(addr string) *Request {
return c.Req(http.MethodOptions, addr)
}
// Patch makes a patch http request.
func (c *Client) Patch(addr string) *Request {
return c.Req(http.MethodPatch, addr)
}
// Post makes a post http request.
func (c *Client) Post(addr string) *Request {
return c.Req(http.MethodPost, addr)
}
// Put makes a put http request.
func (c *Client) Put(addr string) *Request {
return c.Req(http.MethodPut, addr)
}
// Req makes an http request.
func (c *Client) Req(method, addr string) *Request {
address := c.baseURL + addr
if !strings.HasSuffix(c.baseURL, "/") && !strings.HasPrefix(addr, "/") {
address = c.baseURL + "/" + addr
}
return &Request{
Method: method,
Addr: address,
headers: c.headers,
doer: c.doer,
authFn: c.authFn,
encodeFn: c.encodeFn,
backoff: c.backoff,
}
}