-
Notifications
You must be signed in to change notification settings - Fork 1
/
client.go
90 lines (77 loc) · 1.97 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
package httpc
import (
"net/http"
"strings"
"github.com/graymeta/gmkit/backoff"
)
// 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
encodeFn EncodeFn
respRetryFn ResponseErrorFn
authFn AuthFn
backoff backoff.Backoffer
seekParams *seekParams
}
// New returns a new client.
func New(doer Doer, opts ...ClientOptFn) *Client {
c := Client{
doer: doer,
encodeFn: JSONEncode(),
backoff: backoff.NoopBackoff{},
}
for _, o := range opts {
c = o(c)
}
return &c
}
// GET makes a get request.
func (c *Client) GET(addr string) *Request {
return c.Req(http.MethodGet, addr)
}
// HEAD makes a head request.
func (c *Client) HEAD(addr string) *Request {
return c.Req(http.MethodHead, addr)
}
// POST makes a post request.
func (c *Client) POST(addr string) *Request {
return c.Req(http.MethodPost, addr)
}
// DELETE makes a delete request.
func (c *Client) DELETE(addr string) *Request {
return c.Req(http.MethodDelete, addr)
}
// PATCH makes a patch request.
func (c *Client) PATCH(addr string) *Request {
return c.Req(http.MethodPatch, addr)
}
// PUT makes a put 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 c.baseURL != "" &&
!strings.HasSuffix(c.baseURL, "/") &&
!strings.HasPrefix(addr, "/") {
address = c.baseURL + "/" + addr
}
return &Request{
method: method,
addr: address,
doer: c.doer,
authFn: c.authFn,
encodeFn: c.encodeFn,
backoff: c.backoff,
responseErrFn: c.respRetryFn,
seekParams: c.seekParams,
}
}