-
Notifications
You must be signed in to change notification settings - Fork 5
/
gogi.go
101 lines (80 loc) · 1.76 KB
/
gogi.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
97
98
99
100
101
package gogi
import (
"errors"
"net/http"
"net/url"
)
const (
version = "v1"
ua = "gogi/" + version
defaultAPIURL = "https://www.toptal.com"
typePath = "/developers/gitignore/api"
)
// Client for querying API
type Client struct {
client *http.Client
UserAgent string
APIURL *url.URL
}
// NewHTTPClient create new gogi client
func NewHTTPClient(options ...func(*Client) error) (*Client, error) {
c := &Client{
client: http.DefaultClient,
UserAgent: ua,
}
// Default API url
err := WithAPIUrl(defaultAPIURL)(c)
if err != nil {
return nil, err
}
for _, option := range options {
err := option(c)
if err != nil {
return nil, err
}
}
return c, nil
}
// WithAPIUrl sets the API url option for gogi client
func WithAPIUrl(u string) func(*Client) error {
return func(c *Client) error {
apiURL, err := url.Parse(u)
if err != nil {
return err
}
c.APIURL = apiURL
return nil
}
}
// WithHTTPClient sets the client option for gogi client
func WithHTTPClient(client *http.Client) func(*Client) error {
return func(c *Client) error {
if client == nil {
return errors.New("client is nil")
}
c.client = client
return nil
}
}
// NewRequest create new http request
func (c *Client) NewRequest(method, path string, body interface{}) (*http.Request, error) {
relPath, err := url.Parse(path)
if err != nil {
return nil, err
}
u := c.APIURL.ResolveReference(relPath)
req, err := http.NewRequest(method, u.String(), nil)
if err != nil {
return nil, err
}
req.Header.Add("User-Agent", c.UserAgent)
return req, nil
}
// Do make an http request
func (c *Client) Do(req *http.Request) (resp *http.Response, err error) {
resp, err = c.client.Do(req)
if err != nil {
return nil, err
}
return resp, nil
}