request.go 1.1 KB

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