-
-
Notifications
You must be signed in to change notification settings - Fork 2.1k
/
request.go
49 lines (39 loc) · 980 Bytes
/
request.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
package telegram
import (
"context"
"encoding/json"
"io"
"net/http"
"net/url"
"github.com/pkg/errors"
)
func (b *Bot) postForm(ctx context.Context, apiPath string, formData url.Values, result any) error {
apiURL, err := b.apiURL(ctx)
if err != nil {
return err
}
resp, err := http.PostForm(apiURL+apiPath, formData)
if err != nil {
return errors.Wrap(err, "fail to http.PostForm")
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
return errors.Wrap(err, "fail to ioutil.ReadAll")
}
var respInfo struct {
Ok bool `json:"ok"`
ErrorCode int `json:"error_code"`
Description string `json:"description"`
Result any `json:"result"`
}
respInfo.Result = result
err = json.Unmarshal(body, &respInfo)
if err != nil {
return errors.Wrap(err, "fail to json.Unmarshal")
}
if !respInfo.Ok {
return errors.Errorf("api error: [%d]%s", respInfo.ErrorCode, respInfo.Description)
}
return nil
}