forked from go-telegram/bot
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathraw_request.go
More file actions
148 lines (129 loc) · 4.35 KB
/
raw_request.go
File metadata and controls
148 lines (129 loc) · 4.35 KB
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
package bot
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"mime/multipart"
"net/http"
"net/url"
"reflect"
"strings"
)
type apiResponse struct {
OK bool `json:"ok"`
Result json.RawMessage `json:"result,omitempty"`
Description string `json:"description,omitempty"`
ErrorCode int `json:"error_code,omitempty"`
Parameters struct {
RetryAfter int `json:"retry_after,omitempty"`
MigrateToChatID int `json:"migrate_to_chat_id,omitempty"`
} `json:"parameters,omitempty"`
}
func (b *Bot) rawRequest(ctx context.Context, method string, params any, dest any) error {
pr, pw := io.Pipe()
form := multipart.NewWriter(pw)
go func() {
if params != nil && !reflect.ValueOf(params).IsNil() {
_, errFormData := buildRequestForm(form, params)
if errFormData != nil {
if errClose := pw.CloseWithError(fmt.Errorf("error build request form for method %s, %w", method, errFormData)); errClose != nil {
b.errorsHandler(fmt.Errorf("error close pipe writer for method %s, %w", method, errClose))
}
return
}
errFormClose := form.Close()
if errFormClose != nil {
if errClose := pw.CloseWithError(fmt.Errorf("error form close for method %s, %w", method, errFormClose)); errClose != nil {
b.errorsHandler(fmt.Errorf("error close pipe writer for method %s, %w", method, errClose))
}
return
}
}
if errClose := pw.Close(); errClose != nil {
b.errorsHandler(fmt.Errorf("error close pipe writer for method %s, %w", method, errClose))
}
}()
u := b.url + "/bot" + b.token + "/"
if b.testEnvironment {
u += "test/"
}
u += method
if b.isDebug && strings.ToLower(method) != "getupdates" {
requestDebugData, _ := json.Marshal(params)
b.debugHandler("request url: %s, payload: %s", strings.Replace(u, b.token, "***", 1), requestDebugData)
}
req, errRequest := http.NewRequestWithContext(ctx, http.MethodPost, u, pr)
if errRequest != nil {
return fmt.Errorf("error create request for method %s, %w", method, errRequest)
}
req.Header.Add("Content-Type", form.FormDataContentType())
resp, errDo := b.client.Do(req)
if errDo != nil {
if errClose := pr.CloseWithError(errDo); errClose != nil {
b.errorsHandler(fmt.Errorf("error close pipe reader for method %s, %w", method, errClose))
}
var netErr *url.Error
if errors.As(errDo, &netErr) {
netErr.URL = strings.Replace(netErr.URL, b.token, "***", -1)
}
return fmt.Errorf("error do request for method %s, %w", method, errDo)
}
defer func() {
if err := resp.Body.Close(); err != nil {
b.errorsHandler(fmt.Errorf("failed to close response body: %w", err))
}
}()
body, errReadBody := io.ReadAll(resp.Body)
if errReadBody != nil {
return fmt.Errorf("error read response body for method %s, %w", method, errReadBody)
}
r := apiResponse{}
errDecode := json.Unmarshal(body, &r)
if errDecode != nil {
return fmt.Errorf("error decode response body for method %s, %s, %w", method, body, errDecode)
}
if !r.OK {
switch r.ErrorCode {
case http.StatusForbidden:
return fmt.Errorf("%w, %s", ErrorForbidden, r.Description)
case http.StatusBadRequest:
if r.Parameters.MigrateToChatID != 0 {
err := &MigrateError{
Message: fmt.Sprintf("%s: %s", ErrorBadRequest, r.Description),
MigrateToChatID: r.Parameters.MigrateToChatID,
}
return err
}
return fmt.Errorf("%w, %s", ErrorBadRequest, r.Description)
case http.StatusUnauthorized:
return fmt.Errorf("%w, %s", ErrorUnauthorized, r.Description)
case http.StatusNotFound:
return fmt.Errorf("%w, %s", ErrorNotFound, r.Description)
case http.StatusConflict:
return fmt.Errorf("%w, %s", ErrorConflict, r.Description)
case http.StatusTooManyRequests:
err := &TooManyRequestsError{
Message: fmt.Sprintf("%s, %s", ErrorTooManyRequests, r.Description),
RetryAfter: r.Parameters.RetryAfter,
}
return err
default:
return fmt.Errorf("error response from telegram for method %s, %d %s", method, r.ErrorCode, r.Description)
}
}
if !bytes.Equal(r.Result, []byte("[]")) {
if b.isDebug {
b.debugHandler("response from '%s' with payload '%s'", strings.Replace(u, b.token, "***", 1), body)
}
}
if dest != nil {
errDecodeDest := json.Unmarshal(r.Result, dest)
if errDecodeDest != nil {
return fmt.Errorf("error decode response result for method %s, %w", method, errDecodeDest)
}
}
return nil
}