-
Notifications
You must be signed in to change notification settings - Fork 6
/
client.go
246 lines (196 loc) · 4.77 KB
/
client.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
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
package tg
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net/http"
)
type doer interface {
Do(r *http.Request) (*http.Response, error)
}
// Client is Telegram Bot API client structure.
// Create new client with NewClient function.
type Client struct {
// bot api token
token string
// bot api server base url,
// default values is https://api.telegram.org
server string
// http client,
// default values is http.DefaultClient
doer doer
// contains cached bot info
me *User
}
// ClientOption is a function that sets some option for Client.
type ClientOption func(*Client)
// WithServer sets custom server url for Client.
func WithServer(server string) ClientOption {
return func(c *Client) {
c.server = server
}
}
// WithDoer sets custom http client for Client.
func WithDoer(doer *http.Client) ClientOption {
return func(c *Client) {
c.doer = doer
}
}
// New creates new Client with given token and options.
func New(token string, options ...ClientOption) *Client {
c := &Client{
token: token,
server: "https://api.telegram.org",
doer: http.DefaultClient,
}
for _, option := range options {
option(c)
}
return c
}
func (client *Client) Token() string {
return client.token
}
// Execute request at low-level
func (client *Client) execute(ctx context.Context, r *Request) (*Response, error) {
if len(r.files) > 0 {
return client.executeStreaming(
ctx,
func(w io.Writer) httpEncoder { return newMultipartEncoder(w) },
r,
)
}
return client.executeSimple(
ctx,
func(w io.Writer) httpEncoder { return newURLEncodedEncoder(w) },
r,
)
}
func (client *Client) buildCallURL(token, method string) string {
return fmt.Sprintf("%s/bot%s/%s", client.server, token, method)
}
func (client *Client) buildHTTPRequest(
r *Request,
body io.Reader,
contentType string,
) (*http.Request, error) {
url := client.buildCallURL(client.token, r.Method)
req, err := http.NewRequest(http.MethodPost, url, body)
if err != nil {
return nil, fmt.Errorf("new request: %w", err)
}
// set content type
req.Header.Set("Content-Type", contentType)
return req, nil
}
func (client *Client) executeSimple(
ctx context.Context,
newEncoder func(io.Writer) httpEncoder,
r *Request,
) (*Response, error) {
buf := &bytes.Buffer{}
encoder := newEncoder(buf)
if err := r.Encode(encoder); err != nil {
return nil, fmt.Errorf("encode: %w", err)
}
if err := encoder.Close(); err != nil {
return nil, fmt.Errorf("encoder close: %w", err)
}
req, err := client.buildHTTPRequest(
r,
buf,
encoder.ContentType(),
)
if err != nil {
return nil, fmt.Errorf("build http request: %w", err)
}
res, err := client.executeHTTPRequest(ctx, req)
if err != nil {
return nil, fmt.Errorf("execute http request: %w", err)
}
return res, nil
}
func (client *Client) executeHTTPRequest(ctx context.Context, r *http.Request) (*Response, error) {
r = r.WithContext(ctx)
// execute request
res, err := client.doer.Do(r)
if err != nil {
return nil, fmt.Errorf("do request: %w", err)
}
defer res.Body.Close()
// TODO: handle status and content type
// read content
content, err := ioutil.ReadAll(res.Body)
if err != nil {
return nil, fmt.Errorf("read response body: %w", err)
}
response := &Response{
StatusCode: res.StatusCode,
}
// unmarshal content
if err := json.Unmarshal(content, &response); err != nil {
return nil, fmt.Errorf("unmarshal response: %w", err)
}
return response, nil
}
func (client *Client) executeStreaming(
ctx context.Context,
newEncoder func(io.Writer) httpEncoder,
r *Request,
) (*Response, error) {
ctx, cancel := context.WithCancel(ctx)
defer cancel()
pr, pw := io.Pipe()
encoder := newEncoder(pw)
resChan := make(chan *Response)
errChan := make(chan error)
// upload
go func() {
defer pw.Close()
defer encoder.Close()
if err := r.Encode(encoder); err != nil {
errChan <- err
}
}()
// send
go func() {
req, err := client.buildHTTPRequest(r, pr, encoder.ContentType())
if err != nil {
errChan <- fmt.Errorf("build http request: %w", err)
return
}
res, err := client.executeHTTPRequest(ctx, req)
if err != nil {
errChan <- fmt.Errorf("execute http request: %w", err)
return
}
resChan <- res
}()
select {
case err := <-errChan:
return nil, err
case res := <-resChan:
return res, nil
case <-ctx.Done():
return nil, ctx.Err()
}
}
func (client *Client) Invoke(ctx context.Context, req *Request, dst interface{}) error {
res, err := client.execute(ctx, req)
if err != nil {
return fmt.Errorf("execute: %w", err)
}
if !res.Ok {
// TODO: handle bot api errors here
return fmt.Errorf("%d: %s", res.StatusCode, res.Description)
}
if dst != nil {
if err := json.Unmarshal(res.Result, dst); err != nil {
return fmt.Errorf("unmarshal: %w", err)
}
}
return nil
}