request.go 967 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. package telegram
  2. import (
  3. "context"
  4. "encoding/json"
  5. "fmt"
  6. "io"
  7. "net/http"
  8. "net/url"
  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 fmt.Errorf("fail to http.PostForm: %s", err)
  18. }
  19. defer resp.Body.Close()
  20. body, err := io.ReadAll(resp.Body)
  21. if err != nil {
  22. return fmt.Errorf("fail to ioutil.ReadAll: %s", err)
  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 fmt.Errorf("fail to json.Unmarshal: %s", err)
  34. }
  35. if !respInfo.Ok {
  36. return fmt.Errorf("api error: [%d]%s", respInfo.ErrorCode, respInfo.Description)
  37. }
  38. return nil
  39. }