This repository has been archived by the owner on Mar 1, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
rest.go
105 lines (84 loc) · 1.84 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
package eventide
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
)
type RestError struct {
Request *http.Request
Response *http.Response
ResponseBody []byte
Message *ErrorMessage
}
type ErrorMessage struct {
Code int `json:"code"`
Message string `json:"message"`
}
func (e RestError) Error() string {
return fmt.Sprintf("http %d: %s", e.Response.StatusCode, e.ResponseBody)
}
func (c *Client) Request(method string, url string, body io.Reader) ([]byte, error) {
var err error
req, err := http.NewRequest(method, url, body)
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", "application/json")
if c.token != "" {
req.Header.Set("Authorization", c.token)
}
resp, err := c.http.Do(req)
if err != nil {
return nil, err
}
respBody, err := io.ReadAll(resp.Body)
if err != nil {
return nil, err
}
switch resp.StatusCode {
case http.StatusOK:
case http.StatusCreated:
case http.StatusNoContent:
default:
e := RestError{
Request: req,
Response: resp,
ResponseBody: respBody,
}
var mes ErrorMessage
if err := json.Unmarshal(respBody, &mes); err == nil {
e.Message = &mes
}
err = e
}
return respBody, err
}
func (c *Client) GetGatewayURL() (string, error) {
var err error
body, err := c.Request("GET", EndpointGateway, nil)
if err != nil {
return "", err
}
var data GatewayURL
err = json.Unmarshal(body, &data)
return data.URL, err
}
func (c *Client) SendMessage(channelID string, message string) (*Message, error) {
var err error
payload := &MessageSend{
Content: message,
}
dat, err := json.Marshal(payload)
if err != nil {
return nil, err
}
body, err := c.Request("POST", EndpointChannelMessages(channelID), bytes.NewBuffer(dat))
if err != nil {
return nil, err
}
var mes Message
err = json.Unmarshal(body, &mes)
return &mes, err
}