-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient.go
77 lines (60 loc) · 1.58 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
package suzuri
import (
"context"
"fmt"
"io"
"net/http"
"net/url"
"path"
"runtime"
)
const suzuriAPI = "https://suzuri.jp/api/v1"
var userAgent = fmt.Sprintf("SuzuriGo/%s (%s)", version, runtime.Version())
// Client is a SUZURI client for making SUZURI API requests.
type Client struct {
baseURL *url.URL
httpClient *http.Client
token string
}
// NewClient returns a new Client.
func NewClient(token string) *Client {
baseURL, _ := url.ParseRequestURI(suzuriAPI)
return &Client{
baseURL: baseURL,
httpClient: http.DefaultClient,
token: token,
}
}
// SetBaseURL changes the base URL for API requests.
func (c *Client) SetBaseURL(urlStr string) error {
baseURL, err := url.ParseRequestURI(urlStr)
if err != nil {
return err
}
c.baseURL = baseURL
return nil
}
func (c *Client) get(ctx context.Context, endpoint string, params url.Values) (*http.Response, error) {
req, _ := c.newRequest(ctx, "GET", endpoint, params, nil)
resp, err := c.httpClient.Do(req)
if err != nil {
return nil, err
}
return resp, nil
}
func (c *Client) newRequest(ctx context.Context, method, endpoint string, query url.Values, body io.Reader) (*http.Request, error) {
reqURL := *c.baseURL
reqURL.Path = path.Join(c.baseURL.Path, endpoint)
reqURL.RawQuery = query.Encode()
req, err := http.NewRequest(method, reqURL.String(), body)
if err != nil {
return nil, err
}
req = req.WithContext(ctx)
req.Header.Set("Authorization", "Bearer "+c.token)
req.Header.Set("User-Agent", userAgent)
if body != nil {
req.Header.Set("Content-Type", "application/json")
}
return req, nil
}