-
Notifications
You must be signed in to change notification settings - Fork 26
/
request.go
106 lines (91 loc) · 2.33 KB
/
request.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
package bot
import (
"bytes"
"context"
"fmt"
"io"
"net/http"
"time"
"github.com/pkg/errors"
)
var (
DefaultApiHost = "https://api.mixin.one"
DefaultBlazeHost = "blaze.mixin.one"
httpClient *http.Client
httpUri string
blazeUri string
userAgent = "Bot-API-Go-Client"
uid string
sid string
privateKey string
)
func Request(ctx context.Context, method, path string, body []byte, accessToken string) ([]byte, error) {
return RequestWithId(ctx, method, path, body, accessToken, UuidNewV4().String())
}
func RequestWithId(ctx context.Context, method, path string, body []byte, accessToken, requestID string) ([]byte, error) {
req, err := http.NewRequest(method, httpUri+path, bytes.NewReader(body))
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", "Bearer "+accessToken)
req.Header.Set("X-Request-Id", requestID)
req.Header.Set("User-Agent", userAgent)
resp, err := httpClient.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode >= 500 {
return nil, errors.Wrap(ServerError(ctx, nil), fmt.Sprintf("response status code %d", resp.StatusCode))
}
return io.ReadAll(resp.Body)
}
func SimpleRequest(ctx context.Context, method, path string, body []byte) ([]byte, error) {
transport, err := NewTransport(
httpClient.Transport,
uid,
sid,
privateKey,
)
if err != nil {
return nil, err
}
httpClient.Transport = transport
req, err := http.NewRequest(method, httpUri+path, bytes.NewReader(body))
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", "application/json")
resp, err := httpClient.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode >= 500 {
return nil, errors.Wrap(ServerError(ctx, nil), fmt.Sprintf("response status code %d", resp.StatusCode))
}
return io.ReadAll(resp.Body)
}
func init() {
httpClient = &http.Client{Timeout: 30 * time.Second}
httpUri = DefaultApiHost
blazeUri = DefaultBlazeHost
if httpClient.Transport == nil {
httpClient.Transport = http.DefaultTransport
}
}
func WithAPIKey(userId, sessionId, p string) {
uid = userId
sid = sessionId
privateKey = p
}
func SetBaseUri(base string) {
httpUri = base
}
func SetBlazeUri(blaze string) {
blazeUri = blaze
}
func SetUserAgent(ua string) {
userAgent = ua
}