/
client.go
83 lines (64 loc) · 1.62 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
package api
import (
"bytes"
"context"
"encoding/json"
"net/http"
"net/url"
)
type Client struct {
baseURL string
http *http.Client
auth *BasicAuth
}
func (c *Client) Post(ctx context.Context, path string, payload any) (*http.Response, error) {
body := new(bytes.Buffer)
if err := json.NewEncoder(body).Encode(payload); err != nil {
return nil, err
}
req, err := http.NewRequestWithContext(ctx, "POST", c.baseURL+path, body)
if err != nil {
return nil, err
}
if c.auth != nil {
req.SetBasicAuth(c.auth.Username, c.auth.Password)
}
req.Header.Set("Content-Type", "application/json; charset=utf-8")
return c.Do(req)
}
func (c *Client) Get(ctx context.Context, path string, query url.Values) (*http.Response, error) {
req, err := http.NewRequestWithContext(ctx, "GET", c.baseURL+path, nil)
if err != nil {
return nil, err
}
if c.auth != nil {
req.SetBasicAuth(c.auth.Username, c.auth.Password)
}
req.Header.Set("Content-Type", "application/json; charset=utf-8")
req.URL.RawQuery = query.Encode()
return c.Do(req)
}
func (c *Client) Fetch(ctx context.Context, api string) (*http.Response, error) {
req, err := http.NewRequestWithContext(ctx, "GET", api, nil)
if err != nil {
return nil, err
}
if c.auth != nil {
req.SetBasicAuth(c.auth.Username, c.auth.Password)
}
return c.Do(req)
}
func (c *Client) Do(req *http.Request) (*http.Response, error) {
return c.http.Do(req)
}
func New(options []ClientOption) (*Client, error) {
client := &Client{
http: NewHTTPClient(),
}
for _, o := range options {
if err := o(client); err != nil {
return nil, err
}
}
return client, nil
}