http_client.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. // utils/http_client.go
  2. package utils
  3. import (
  4. "bytes"
  5. "context"
  6. "crypto/tls"
  7. "encoding/json"
  8. "fmt"
  9. "io"
  10. "net/http"
  11. "time"
  12. )
  13. type HTTPClient interface {
  14. PostJSON(ctx context.Context, url string, body interface{}) ([]byte, error)
  15. }
  16. type httpClient struct {
  17. client *http.Client
  18. }
  19. func NewHttpClient(timeout time.Duration, isSkipSSLVerify bool) HTTPClient {
  20. return &httpClient{
  21. client: &http.Client{
  22. Timeout: timeout,
  23. Transport: &http.Transport{
  24. TLSClientConfig: &tls.Config{
  25. InsecureSkipVerify: isSkipSSLVerify, // 跳过 SSL 验证
  26. },
  27. MaxIdleConns: 100,
  28. IdleConnTimeout: 90 * time.Second,
  29. DisableCompression: true,
  30. },
  31. },
  32. }
  33. }
  34. func (c *httpClient) PostJSON(ctx context.Context, url string, body interface{}) ([]byte, error) {
  35. // 创建请求体
  36. var reqBody []byte
  37. if body != nil {
  38. var err error
  39. reqBody, err = json.Marshal(body)
  40. if err != nil {
  41. return nil, fmt.Errorf("JSON序列化失败: %w", err)
  42. }
  43. }
  44. // 创建HTTP请求
  45. req, err := http.NewRequestWithContext(ctx, "POST", url, bytes.NewReader(reqBody))
  46. if err != nil {
  47. return nil, fmt.Errorf("创建请求失败: %w", err)
  48. }
  49. req.Header.Set("Content-Type", "application/json")
  50. req.Header.Set("Accept", "application/json")
  51. // 发送请求
  52. resp, err := c.client.Do(req)
  53. if err != nil {
  54. return nil, fmt.Errorf("网络请求失败: %w", err)
  55. }
  56. defer resp.Body.Close()
  57. // 检查状态码
  58. if resp.StatusCode < 200 || resp.StatusCode >= 300 {
  59. return nil, fmt.Errorf("非成功状态码: %d", resp.StatusCode)
  60. }
  61. // 读取响应内容
  62. respBody, err := io.ReadAll(resp.Body)
  63. if err != nil {
  64. return nil, fmt.Errorf("读取响应失败: %w", err)
  65. }
  66. return respBody, nil
  67. }