-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapi.go
53 lines (42 loc) · 1.15 KB
/
api.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
package main
import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"golang.org/x/xerrors"
)
func call(ctx context.Context, token, method string, dst interface{}) error {
uri := fmt.Sprintf("https://api.telegram.org/bot%s/%s", token, method)
req, err := http.NewRequestWithContext(ctx, http.MethodGet, uri, nil)
if err != nil {
return xerrors.Errorf("build request: %w", err)
}
res, err := http.DefaultClient.Do(req)
if err != nil {
return xerrors.Errorf("execute request: %w", err)
}
defer res.Body.Close()
body, err := io.ReadAll(res.Body)
if err != nil {
return xerrors.Errorf("read body: %w", err)
}
var response struct {
Ok bool `json:"ok"`
Description string `json:"description"`
Result json.RawMessage `json:"result"`
}
if err := json.Unmarshal(body, &response); err != nil {
return xerrors.Errorf("unmarshal body: %w", err)
}
if !response.Ok {
return xerrors.Errorf("call error: %s (%d)", response.Description, res.StatusCode)
}
if dst != nil {
if err := json.Unmarshal(response.Result, dst); err != nil {
return xerrors.Errorf("unmarshal result: %w", err)
}
}
return nil
}