-
Notifications
You must be signed in to change notification settings - Fork 0
/
api.go
78 lines (66 loc) · 1.67 KB
/
api.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
78
// Package rbxweb provides API routines to interact with Roblox's web API.
package rbxweb
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"net/http"
"net/url"
)
// Client is the [http.Client] used to make Roblox API requests.
var Client = &http.Client{}
var (
ErrBadStatus = errors.New("bad status")
ErrNoData = errors.New("no data")
)
// Request performs a Roblox API request given a method, url returned by
// [GetURL], body and data interfaces to use as data to send and to recieve.
func Request(method, url string, body, data interface{}) error {
buf := new(bytes.Buffer)
if body != nil {
if err := json.NewEncoder(buf).Encode(body); err != nil {
return err
}
}
req, err := http.NewRequest(method, url, buf)
if err != nil {
return err
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Accept", "application/json")
resp, err := Client.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
dec := json.NewDecoder(resp.Body)
if resp.StatusCode != http.StatusOK {
// Return API error only if such error exists
e := new(errorsResponse)
if err := dec.Decode(e); err == nil {
return e
}
return fmt.Errorf("%w: %s", ErrBadStatus, resp.Status)
}
if data != nil {
return dec.Decode(data)
}
return nil
}
// GetURL constructs a Roblox web API URL with the given service as the
// subdomain, and the given arguments, with HTTPS as the protocol.
func GetURL(service string, path string, query url.Values) string {
url := url.URL{
Scheme: "https",
Host: "roblox.com",
Path: path,
}
if query != nil {
url.RawQuery = query.Encode()
}
if service != "" {
url.Host = service + "." + url.Host
}
return url.String()
}