request.go 980 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. package telegram
  2. import (
  3. "context"
  4. "encoding/json"
  5. "io"
  6. "net/http"
  7. "net/url"
  8. "github.com/pkg/errors"
  9. )
  10. func (b *Bot) postForm(ctx context.Context, apiPath string, formData url.Values, result any) error {
  11. apiURL, err := b.apiURL(ctx)
  12. if err != nil {
  13. return err
  14. }
  15. resp, err := http.PostForm(apiURL+apiPath, formData)
  16. if err != nil {
  17. return errors.Wrap(err, "fail to http.PostForm")
  18. }
  19. defer resp.Body.Close()
  20. body, err := io.ReadAll(resp.Body)
  21. if err != nil {
  22. return errors.Wrap(err, "fail to ioutil.ReadAll")
  23. }
  24. var respInfo struct {
  25. Ok bool `json:"ok"`
  26. ErrorCode int `json:"error_code"`
  27. Description string `json:"description"`
  28. Result any `json:"result"`
  29. }
  30. respInfo.Result = result
  31. err = json.Unmarshal(body, &respInfo)
  32. if err != nil {
  33. return errors.Wrap(err, "fail to json.Unmarshal")
  34. }
  35. if !respInfo.Ok {
  36. return errors.Errorf("api error: [%d]%s", respInfo.ErrorCode, respInfo.Description)
  37. }
  38. return nil
  39. }