aboutsummaryrefslogtreecommitdiff
path: root/web/revolt/http.go
blob: 377eb6200f23e6b2fcbd25554f4b71b0d9f9f3bf (plain)
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
package revolt

import (
	"bytes"
	"context"
	"io"
	"net/http"

	"within.website/x/web"
)

func (c *Client) RequestWithPathAndContentType(ctx context.Context, method, path, contentType string, data []byte) ([]byte, error) {
	reqBody := bytes.NewBuffer(data)

	<-c.Ticker.C

	// Prepare request
	req, err := http.NewRequestWithContext(ctx, method, path, reqBody)
	if err != nil {
		return []byte{}, err
	}

	req.Header.Set("content-type", contentType)

	// Set auth headers
	if c.SelfBot == nil {
		req.Header.Set("x-bot-token", c.Token)
	} else if c.SelfBot.SessionToken != "" {
		req.Header.Set("x-session-token", c.SelfBot.SessionToken)
	}

	// Send request
	resp, err := c.HTTP.Do(req)

	if err != nil {
		return []byte{}, err
	}

	defer resp.Body.Close()

	if !(resp.StatusCode >= 200 && resp.StatusCode < 300) {
		return []byte{}, web.NewError(200, resp)
	}

	body, err := io.ReadAll(resp.Body)
	if err != nil {
		return []byte{}, err
	}

	return body, nil
}

// Send http request
func (c Client) Request(ctx context.Context, method, path string, data []byte) ([]byte, error) {
	reqBody := bytes.NewBuffer(data)

	<-c.Ticker.C

	// Prepare request
	req, err := http.NewRequestWithContext(ctx, method, c.BaseURL+path, reqBody)
	if err != nil {
		return []byte{}, err
	}

	req.Header.Set("content-type", "application/json")

	// Set auth headers
	if c.SelfBot == nil {
		req.Header.Set("x-bot-token", c.Token)
	} else if c.SelfBot.SessionToken != "" {
		req.Header.Set("x-session-token", c.SelfBot.SessionToken)
	}

	// Send request
	resp, err := c.HTTP.Do(req)

	if err != nil {
		return []byte{}, err
	}

	defer resp.Body.Close()

	if !(resp.StatusCode >= 200 && resp.StatusCode < 300) {
		return []byte{}, web.NewError(200, resp)
	}

	body, err := io.ReadAll(resp.Body)
	if err != nil {
		return []byte{}, err
	}

	return body, nil
}