request.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. package service
  2. import (
  3. "bytes"
  4. "context"
  5. "crypto/tls"
  6. "encoding/json"
  7. "fmt"
  8. "io"
  9. "net/http"
  10. "time"
  11. )
  12. type RequestService interface {
  13. Request(ctx context.Context, formData map[string]interface{},apiUrl string, tokenName string,token string) ([]byte, error)
  14. }
  15. func NewRequestService(
  16. service *Service,
  17. ) RequestService {
  18. httpClient := &http.Client{
  19. Transport: &http.Transport{
  20. TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
  21. MaxIdleConns: 500, // 最大空闲连接数
  22. MaxIdleConnsPerHost: 300, // 每个主机的最大空闲连接数
  23. IdleConnTimeout: 90 * time.Second, // 空闲连接超时时间
  24. },
  25. Timeout: 30 * time.Second, // 请求超时时间
  26. }
  27. return &requestService{
  28. Service: service,
  29. httpClient: httpClient,
  30. }
  31. }
  32. type requestService struct {
  33. *Service
  34. httpClient *http.Client
  35. }
  36. func (s *requestService) Request(ctx context.Context, formData map[string]interface{},apiUrl string, tokenName string,token string) ([]byte, error) {
  37. jsonData, err := json.Marshal(formData)
  38. if err != nil {
  39. return nil, err
  40. }
  41. req, err := http.NewRequestWithContext(ctx, "POST", apiUrl, bytes.NewBuffer(jsonData))
  42. if err != nil {
  43. return nil, fmt.Errorf("创建 HTTP 请求失败: %w", err)
  44. }
  45. req.Header.Set("Content-Type", "application/json")
  46. if token != "" {
  47. req.Header.Set(tokenName, token)
  48. }
  49. resp, err := s.httpClient.Do(req)
  50. if err != nil {
  51. return nil, fmt.Errorf("发送 HTTP 请求失败 (isSmall: %t): %w", err)
  52. }
  53. defer resp.Body.Close()
  54. body, err := io.ReadAll(resp.Body)
  55. if err != nil {
  56. return nil, fmt.Errorf("读取响应体失败 (isSmall: %t): %w", err)
  57. }
  58. if resp.StatusCode != http.StatusOK {
  59. return nil, fmt.Errorf("HTTP 错误 (isSmall: %t): 状态码 %d, 响应: %s", resp.StatusCode, string(body))
  60. }
  61. return body, nil
  62. }