-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
74 lines (62 loc) · 1.47 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
package dbl_go
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"runtime"
)
type DBL struct {
baseURL *url.URL
userAgent string
token string
httpClient *http.Client
}
// NewDBL creates a new top.gg client with the given token and HTTP client
func NewDBL(token string, client *http.Client) *DBL {
if client == nil {
client = &http.Client{}
}
base, _ := url.Parse(BaseURL)
return &DBL{
baseURL: base,
userAgent: fmt.Sprintf("dbl-go/%s (%s) Golang/%s", Version, runtime.GOOS, runtime.Version()),
token: token,
httpClient: client,
}
}
func (c *DBL) newRequest(method, path string, body interface{}) (*http.Request, error) {
rel := &url.URL{Path: "/api" + path}
u := c.baseURL.ResolveReference(rel)
fmt.Println("Calling ", rel)
var buf io.ReadWriter
if body != nil {
buf = new(bytes.Buffer)
err := json.NewEncoder(buf).Encode(body)
if err != nil {
return nil, err
}
}
req, err := http.NewRequest(method, u.String(), buf)
if err != nil {
return nil, err
}
if body != nil {
req.Header.Set("Content-Type", "application/json")
}
req.Header.Set("Accept", "application/json")
req.Header.Set("User-Agent", c.userAgent)
req.Header.Set("Authorization", c.token)
return req, nil
}
func (c *DBL) do(req *http.Request, v interface{}) (*http.Response, error) {
resp, err := c.httpClient.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
err = json.NewDecoder(resp.Body).Decode(v)
return resp, err
}