-
Notifications
You must be signed in to change notification settings - Fork 7
/
client.go
66 lines (60 loc) · 1.42 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
package osuapi
import (
"encoding/json"
"errors"
"io/ioutil"
"net/http"
"net/url"
)
// Client is an osu! API client that is able to make API requests.
type Client struct {
client *http.Client
key string
}
// NewClient generates a new Client based on an API key.
func NewClient(key string) *Client {
c := &Client{&http.Client{}, key}
return c
}
func (c Client) makerq(endpoint string, queryString url.Values) ([]byte, error) {
queryString.Set("k", c.key)
req, err := http.NewRequest("GET", "https://osu.ppy.sh/api/"+endpoint+"?"+queryString.Encode(), nil)
if err != nil {
return nil, err
}
// if we are rate limiting requests, then wait before making request
if requestsAvailable != nil {
<-requestsAvailable
}
resp, err := c.client.Do(req)
if err != nil {
return nil, err
}
data, err := ioutil.ReadAll(resp.Body)
defer resp.Body.Close()
return data, err
}
type testResponse struct {
Error string `json:"error"`
}
// Test makes sure the API is working (and the API key is valid).
func (c Client) Test() error {
resp, err := c.makerq("get_user", url.Values{
"u": []string{
"2",
},
})
if err != nil {
return err
}
var tr testResponse
err = json.Unmarshal(resp, &tr)
// Ignore cannot unmarshal stuff
if err != nil && err.Error() != "json: cannot unmarshal array into Go value of type osuapi.testResponse" {
return err
}
if tr.Error != "" {
return errors.New("osuapi: " + tr.Error)
}
return nil
}