-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathclient.go
65 lines (52 loc) · 1.32 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
package kutt
import (
"io"
"io/ioutil"
"net/http"
"github.com/pkg/errors"
)
const version = "0.0.1"
const baseURL = "https://kutt.it"
func init() {
defaultUserAgent = "kutt-go/" + version + " (+https://github.com/raahii/kutt-go)"
}
var defaultUserAgent string
type Client struct {
HTTPClient *http.Client
ApiKey string
BaseURL string
UserAgent string
}
func NewClient(apiKey string) *Client {
var cli Client
cli.ApiKey = apiKey
cli.BaseURL = baseURL
cli.UserAgent = defaultUserAgent
return &cli
}
func (cli *Client) getUA() string {
if cli.UserAgent != "" {
return cli.UserAgent
}
return defaultUserAgent
}
func (cli *Client) httpClient() *http.Client {
if cli.HTTPClient != nil {
return cli.HTTPClient
}
return http.DefaultClient
}
func (cli *Client) do(req *http.Request) (*http.Response, error) {
req.Header.Set("X-API-Key", cli.ApiKey)
req.Header.Set("User-Agent", cli.getUA())
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Accept", "application/json")
return cli.httpClient().Do(req)
}
func (cli *Client) error(statusCode int, body io.Reader) error {
buf, err := ioutil.ReadAll(body)
if err != nil || len(buf) == 0 {
return errors.Errorf("request failed with status code %d", statusCode)
}
return errors.Errorf("StatusCode: %d, Error: %s", statusCode, string(buf))
}