-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient.go
102 lines (83 loc) · 2.02 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
package tg
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"log/slog"
"net/http"
"time"
)
const BaseURL = "https://api.telegram.org/bot"
type Client struct {
log *slog.Logger
httpClient HTTPClientDoer
baseURL string
token string
}
type response struct {
Success bool `json:"ok"`
Result json.RawMessage `json:"result"`
ErrorCode int `json:"error_code"`
Description string `json:"description"`
}
func New(token string, opts ...Option) *Client {
c := &Client{token: token}
defaultOpts := []Option{
WithLogger(slog.New(slog.NewJSONHandler(io.Discard, nil))),
WithHTTPClient(&http.Client{Timeout: 30 * time.Second}),
WithBaseURL(BaseURL),
}
for _, opt := range append(defaultOpts, opts...) {
opt(c)
}
return c
}
func (c *Client) Call(ctx context.Context, value Sendable) (json.RawMessage, error) {
req, err := http.NewRequestWithContext(
ctx,
"POST",
fmt.Sprintf("%s%s/%s", c.baseURL, c.token, value.Method()),
bytes.NewReader(value.Params()),
)
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", "application/json; charset=utf-8")
resp, err := c.httpClient.Do(req)
if err != nil {
return nil, err
}
defer func() { _ = resp.Body.Close() }()
switch resp.StatusCode {
case http.StatusOK:
case http.StatusBadRequest:
case http.StatusUnauthorized:
case http.StatusConflict:
default:
_, _ = io.Copy(io.Discard, resp.Body)
return nil, fmt.Errorf("unexpected response status code: %d", resp.StatusCode)
}
return c.parseResponse(resp.Body)
}
func (c *Client) parseResponse(r io.Reader) (json.RawMessage, error) {
var resp response
if err := json.NewDecoder(r).Decode(&resp); err != nil {
return nil, fmt.Errorf("decode response body: %w", err)
}
if !resp.Success {
return nil, &Error{
Code: resp.ErrorCode,
Message: resp.Description,
}
}
return resp.Result, nil
}
func DecodeJSON[T any](payload []byte) (T, error) {
var (
val = new(T)
err = json.Unmarshal(payload, val)
)
return *val, err
}