| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778 |
- // utils/http_client.go
- package utils
- import (
- "bytes"
- "context"
- "crypto/tls"
- "encoding/json"
- "fmt"
- "io"
- "net/http"
- "time"
- )
- type HTTPClient interface {
- PostJSON(ctx context.Context, url string, body interface{}) ([]byte, error)
- }
- type httpClient struct {
- client *http.Client
- }
- func NewHttpClient(timeout time.Duration, isSkipSSLVerify bool) HTTPClient {
- return &httpClient{
- client: &http.Client{
- Timeout: timeout,
- Transport: &http.Transport{
- TLSClientConfig: &tls.Config{
- InsecureSkipVerify: isSkipSSLVerify, // 跳过 SSL 验证
- },
- MaxIdleConns: 100,
- IdleConnTimeout: 90 * time.Second,
- DisableCompression: true,
- },
- },
- }
- }
- func (c *httpClient) PostJSON(ctx context.Context, url string, body interface{}) ([]byte, error) {
- // 创建请求体
- var reqBody []byte
- if body != nil {
- var err error
- reqBody, err = json.Marshal(body)
- if err != nil {
- return nil, fmt.Errorf("JSON序列化失败: %w", err)
- }
- }
- // 创建HTTP请求
- req, err := http.NewRequestWithContext(ctx, "POST", url, bytes.NewReader(reqBody))
- if err != nil {
- return nil, fmt.Errorf("创建请求失败: %w", err)
- }
- req.Header.Set("Content-Type", "application/json")
- req.Header.Set("Accept", "application/json")
- // 发送请求
- resp, err := c.client.Do(req)
- if err != nil {
- return nil, fmt.Errorf("网络请求失败: %w", err)
- }
- defer resp.Body.Close()
- // 检查状态码
- if resp.StatusCode < 200 || resp.StatusCode >= 300 {
- return nil, fmt.Errorf("非成功状态码: %d", resp.StatusCode)
- }
- // 读取响应内容
- respBody, err := io.ReadAll(resp.Body)
- if err != nil {
- return nil, fmt.Errorf("读取响应失败: %w", err)
- }
- return respBody, nil
- }
|