This repository has been archived by the owner on Jul 2, 2021. It is now read-only.
/
rest.go
107 lines (90 loc) · 2.57 KB
/
rest.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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
package providers
import (
"bytes"
"encoding/json"
"fmt"
"github.com/kislball/goocord"
"io/ioutil"
"net/http"
"strconv"
"strings"
"time"
)
// HTTPRestProvider is a basic RestProvider used by default.
// Uses HTTP to communicate with Discord's API
type HTTPRestProvider struct {
// Authentication header used by this HTTPRestProvider
Auth string
// Base API url
URL string
// Client used for requests
Client *http.Client
}
// NewHTTPRestProvider creates a new HTTPRestProvider
func NewHTTPRestProvider(auth string) *HTTPRestProvider {
return &HTTPRestProvider{
auth,
"https://discord.com/api/v9",
&http.Client{},
}
}
// UseAuth sets a new Authorization header
func (h *HTTPRestProvider) UseAuth(auth string) {
h.Auth = auth
}
// UseAPI changes API url
func (h *HTTPRestProvider) UseAPI(url string) {
h.URL = url
}
// getURL concats endpoint and base API url
func (h *HTTPRestProvider) getURL(endpoint string) string {
return fmt.Sprintf("%s/%s", h.URL, endpoint)
}
// convertBody transforms data to array of bytes
func (h *HTTPRestProvider) convertBody(data interface{}) (d []byte, err error) {
return json.Marshal(data)
}
// setHeaders takes map of headers and applies them to the req
func (h *HTTPRestProvider) setHeaders(req *http.Request, headers map[string]string) {
for k, v := range headers {
req.Header.Set(k, v)
}
}
// transformResponse transforms http.Response into RestResponse
func (h *HTTPRestProvider) transformResponse(resp *http.Response) (res *RestResponse, err error) {
headers := make(map[string]string)
for k, v := range resp.Header {
headers[k] = strings.Join(v, " ")
}
b, err := ioutil.ReadAll(resp.Body)
if err != nil {
return
}
var body interface{}
err = json.Unmarshal(b, &body)
if err != nil {
return
}
return &RestResponse{
resp.StatusCode,
headers,
body,
}, nil
}
// Request sends requests to Discord
func (h *HTTPRestProvider) Request(method string, endpoint string, headers map[string]string, body interface{}) (resp *RestResponse, err error) {
url := h.getURL(endpoint)
d, err := h.convertBody(body)
req, err := http.NewRequest(method, url, bytes.NewBuffer(d))
h.setHeaders(req, headers)
req.Header.Set("Authorization", h.Auth)
req.Header.Set("User-Agent", fmt.Sprintf("DiscordBot (https://github.com/kislball/goocord, %s)", goocord.Version))
respRaw, err := h.Client.Do(req)
if respRaw.StatusCode == 429 {
retry, _ := strconv.Atoi(respRaw.Header.Get("Retry-After"))
time.Sleep(time.Duration(retry) * time.Second)
resp, err = h.Request(method, endpoint, headers, body)
return
}
return h.transformResponse(respRaw)
}