forked from alexejk/go-warcraftlogs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
77 lines (60 loc) · 1.46 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 warcraftlogs
import (
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"strings"
"time"
)
// WarcraftLogs Client
type WarcraftLogs struct {
client http.Client
apiToken string
endpoint string
}
// New WarcraftLogs Client, with required API Token.
// Currently using v1 API endpoint as default
func New(apiToken string) *WarcraftLogs {
api := &WarcraftLogs{
endpoint: "https://www.warcraftlogs.com/v1/",
client: http.Client{
Timeout: time.Second * 2,
},
apiToken: apiToken,
}
return api
}
// SetEndpoint allows customizing API Endpoint that client will use.
// If provided endoint does not end with a trailing slash, it will be added
func (w *WarcraftLogs) SetEndpoint(endpoint string) {
w.endpoint = endpoint
if !strings.HasSuffix(w.endpoint, "/") {
w.endpoint = w.endpoint + "/"
}
}
// Support function to make an authenticated GET call and parse response JSON to a responseHolder.
func (w *WarcraftLogs) get(path string, responseHolder interface{}) error {
url := fmt.Sprintf("%s%s?api_key=%s", w.endpoint, path, w.apiToken)
req, err := http.NewRequest("GET", url, nil)
if err != nil {
log.Fatal(err)
}
res, getErr := w.client.Do(req)
if getErr != nil {
log.Fatal(getErr)
return getErr
}
body, readErr := ioutil.ReadAll(res.Body)
if readErr != nil {
log.Fatal(readErr)
return readErr
}
jsonErr := json.Unmarshal(body, responseHolder)
if jsonErr != nil {
log.Fatal(jsonErr)
return jsonErr
}
return nil
}