-
Notifications
You must be signed in to change notification settings - Fork 31
/
http.go
166 lines (136 loc) · 3.8 KB
/
http.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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
package stream_chat
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/url"
)
type Error struct {
Code int `json:"code"`
Message string `json:"message"`
ExceptionFields map[string]string `json:"exception_fields,omitempty"`
StatusCode int `json:"StatusCode"`
Duration string `json:"duration"`
MoreInfo string `json:"more_info"`
RateLimit *RateLimitInfo `json:"-"`
}
func (e Error) Error() string {
return e.Message
}
// Response is the base response returned to client. It contains rate limit information.
// All specific response returned to the client should embed this type.
type Response struct {
RateLimitInfo *RateLimitInfo `json:"ratelimit"`
}
func (c *Client) parseResponse(resp *http.Response, result interface{}) error {
if resp.Body == nil {
return errors.New("http body is nil")
}
defer resp.Body.Close()
b, err := io.ReadAll(resp.Body)
if err != nil {
return fmt.Errorf("failed to read HTTP response: %w", err)
}
if resp.StatusCode >= 399 {
var apiErr Error
err := json.Unmarshal(b, &apiErr)
if err != nil {
// IP rate limit errors sent by our Edge infrastructure are not JSON encoded.
// If decode fails here, we need to handle this manually.
apiErr.Message = string(b)
apiErr.StatusCode = resp.StatusCode
return apiErr
}
// Include rate limit information.
apiErr.RateLimit = NewRateLimitFromHeaders(resp.Header)
return apiErr
}
if _, ok := result.(*Response); !ok {
// Unmarshal the body only when it is expected.
err = json.Unmarshal(b, result)
if err != nil {
return fmt.Errorf("cannot unmarshal body: %w", err)
}
}
return c.addRateLimitInfo(resp.Header, result)
}
func (c *Client) requestURL(path string, values url.Values) (string, error) {
u, err := url.Parse(c.BaseURL + "/" + path)
if err != nil {
return "", errors.New("url.Parse: " + err.Error())
}
if values == nil {
values = make(url.Values)
}
values.Add("api_key", c.apiKey)
u.RawQuery = values.Encode()
return u.String(), nil
}
func (c *Client) newRequest(ctx context.Context, method, path string, params url.Values, data interface{}) (*http.Request, error) {
u, err := c.requestURL(path, params)
if err != nil {
return nil, err
}
r, err := http.NewRequestWithContext(ctx, method, u, http.NoBody)
if err != nil {
return nil, err
}
c.setHeaders(r)
switch t := data.(type) {
case nil:
r.Body = nil
case io.ReadCloser:
r.Body = t
case io.Reader:
r.Body = io.NopCloser(t)
default:
b, err := json.Marshal(data)
if err != nil {
return nil, err
}
r.Body = io.NopCloser(bytes.NewReader(b))
}
return r, nil
}
func (c *Client) setHeaders(r *http.Request) {
r.Header.Set("Content-Type", "application/json")
r.Header.Set("X-Stream-Client", versionHeader())
r.Header.Set("Authorization", c.authToken)
r.Header.Set("Stream-Auth-Type", "jwt")
}
func (c *Client) makeRequest(ctx context.Context, method, path string, params url.Values, data, result interface{}) error {
r, err := c.newRequest(ctx, method, path, params, data)
if err != nil {
return err
}
resp, err := c.HTTP.Do(r)
if err != nil {
select {
case <-ctx.Done():
// If we got an error, and the context has been canceled,
// return context's error which is more useful.
return ctx.Err()
default:
}
return err
}
return c.parseResponse(resp, result)
}
func (c *Client) addRateLimitInfo(headers http.Header, result interface{}) error {
rl := map[string]interface{}{
"ratelimit": NewRateLimitFromHeaders(headers),
}
b, err := json.Marshal(rl)
if err != nil {
return fmt.Errorf("cannot marshal rate limit info: %w", err)
}
err = json.Unmarshal(b, result)
if err != nil {
return fmt.Errorf("cannot unmarshal rate limit info: %w", err)
}
return nil
}