-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbs-api.go
More file actions
51 lines (45 loc) · 970 Bytes
/
bs-api.go
File metadata and controls
51 lines (45 loc) · 970 Bytes
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
package bsapi
import (
"bytes"
"context"
"net/http"
jsoniter "github.com/json-iterator/go"
)
const apiUrl = `https://api.brawlstars.com/v1`
var json = jsoniter.ConfigCompatibleWithStandardLibrary
type BsApi struct {
token string
}
func (api BsApi) makeRequest(ctx context.Context, urlSuffix string) ([]byte, error) {
client := http.Client{}
req, err := http.NewRequestWithContext(ctx, "GET", apiUrl+urlSuffix, nil)
if err != nil {
return nil, err
}
req.Header.Set("Authorization", "Bearer "+api.token)
if err != nil {
return nil, err
}
resp, err := client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
buf := bytes.Buffer{}
buf.ReadFrom(resp.Body)
data := buf.Bytes()
if resp.StatusCode == http.StatusOK {
return data, nil
}
ce := ClientError{}
err = json.Unmarshal(data, &ce)
if err != nil {
return nil, err
}
return nil, ce
}
func NewApi(token string) BsApi {
bs := BsApi{}
bs.token = token
return bs
}