network_client.go 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187
  1. package utils
  2. import (
  3. "bytes"
  4. "context"
  5. "encoding/json"
  6. "fmt"
  7. "io"
  8. "mime/multipart"
  9. "net/http"
  10. "os"
  11. "path/filepath"
  12. "time"
  13. )
  14. // HTTPClient 封装HTTP客户端
  15. type HTTPClient struct {
  16. client *http.Client
  17. baseURL string
  18. Authorization string
  19. }
  20. // NewHTTPClient 创建新的HTTP客户端
  21. func NewHTTPClient(baseURL, token string) *HTTPClient {
  22. return &HTTPClient{
  23. client: &http.Client{
  24. Timeout: 60 * time.Second,
  25. },
  26. baseURL: baseURL,
  27. Authorization: token,
  28. }
  29. }
  30. // SetToken 设置认证token
  31. func (c *HTTPClient) SetToken(token string) {
  32. c.Authorization = token
  33. }
  34. // Get 发起GET请求
  35. func (c *HTTPClient) Get(ctx context.Context, endpoint string, headers map[string]string) (*http.Response, error) {
  36. url := c.baseURL + endpoint
  37. req, err := http.NewRequestWithContext(ctx, "GET", url, nil)
  38. if err != nil {
  39. return nil, fmt.Errorf("创建请求失败: %w", err)
  40. }
  41. // 设置默认headers
  42. req.Header.Set("Content-Type", "application/json")
  43. if c.Authorization != "" {
  44. req.Header.Set("Authorization", "Bearer "+c.Authorization)
  45. }
  46. // 设置自定义headers
  47. for key, value := range headers {
  48. req.Header.Set(key, value)
  49. }
  50. return c.client.Do(req)
  51. }
  52. // Post 发起POST请求
  53. func (c *HTTPClient) Post(ctx context.Context, endpoint string, data interface{}, headers map[string]string) (*http.Response, error) {
  54. url := c.baseURL + endpoint
  55. var reqBody io.Reader
  56. if data != nil {
  57. jsonData, err := json.Marshal(data)
  58. if err != nil {
  59. return nil, fmt.Errorf("序列化请求数据失败: %w", err)
  60. }
  61. reqBody = bytes.NewBuffer(jsonData)
  62. }
  63. req, err := http.NewRequestWithContext(ctx, "POST", url, reqBody)
  64. if err != nil {
  65. return nil, fmt.Errorf("创建请求失败: %w", err)
  66. }
  67. // 设置默认headers
  68. req.Header.Set("Content-Type", "application/json")
  69. if c.Authorization != "" {
  70. req.Header.Set("Authorization", "Bearer "+c.Authorization)
  71. }
  72. // 设置自定义headers
  73. for key, value := range headers {
  74. req.Header.Set(key, value)
  75. }
  76. return c.client.Do(req)
  77. }
  78. // UploadFile 上传文件
  79. func (c *HTTPClient) UploadFile(ctx context.Context, endpoint string, filePath string, fieldName string, headers map[string]string, result interface{}) error {
  80. url := c.baseURL + endpoint
  81. // 打开文件
  82. file, err := os.Open(filePath)
  83. if err != nil {
  84. return fmt.Errorf("打开文件失败: %w", err)
  85. }
  86. defer file.Close()
  87. // 创建multipart表单
  88. var buf bytes.Buffer
  89. writer := multipart.NewWriter(&buf)
  90. // 添加文件字段
  91. fileWriter, err := writer.CreateFormFile(fieldName, filepath.Base(filePath))
  92. if err != nil {
  93. return fmt.Errorf("创建表单文件字段失败: %w", err)
  94. }
  95. // 复制文件内容到表单
  96. _, err = io.Copy(fileWriter, file)
  97. if err != nil {
  98. return fmt.Errorf("复制文件内容失败: %w", err)
  99. }
  100. // 关闭表单写入器
  101. err = writer.Close()
  102. if err != nil {
  103. return fmt.Errorf("关闭表单写入器失败: %w", err)
  104. }
  105. // 创建请求
  106. req, err := http.NewRequestWithContext(ctx, "POST", url, &buf)
  107. if err != nil {
  108. return fmt.Errorf("创建请求失败: %w", err)
  109. }
  110. // 设置内容类型为multipart表单
  111. req.Header.Set("Content-Type", writer.FormDataContentType())
  112. // 设置认证头
  113. if c.Authorization != "" {
  114. req.Header.Set("Authorization", "Bearer "+c.Authorization)
  115. }
  116. // 设置自定义headers
  117. for key, value := range headers {
  118. req.Header.Set(key, value)
  119. }
  120. resp, err := c.client.Do(req)
  121. if err != nil {
  122. return err
  123. }
  124. return c.ParseJSON(resp, result)
  125. }
  126. // ParseJSON 解析JSON响应
  127. func (c *HTTPClient) ParseJSON(resp *http.Response, result interface{}) error {
  128. defer resp.Body.Close()
  129. body, err := io.ReadAll(resp.Body)
  130. if err != nil {
  131. return fmt.Errorf("读取响应体失败: %w", err)
  132. }
  133. if resp.StatusCode >= 400 {
  134. return fmt.Errorf("请求失败 status=%d body=%s", resp.StatusCode, string(body))
  135. }
  136. if err := json.Unmarshal(body, result); err != nil {
  137. return fmt.Errorf("解析JSON失败: %w, body=%s", err, string(body))
  138. }
  139. return nil
  140. }
  141. // GetJSON 发起GET请求并解析JSON响应
  142. func (c *HTTPClient) GetJSON(ctx context.Context, endpoint string, result interface{}, headers map[string]string) error {
  143. resp, err := c.Get(ctx, endpoint, headers)
  144. if err != nil {
  145. return err
  146. }
  147. return c.ParseJSON(resp, result)
  148. }
  149. // PostJSON 发起POST请求并解析JSON响应
  150. func (c *HTTPClient) PostJSON(ctx context.Context, endpoint string, data interface{}, result interface{}, headers map[string]string) error {
  151. resp, err := c.Post(ctx, endpoint, data, headers)
  152. if err != nil {
  153. return err
  154. }
  155. return c.ParseJSON(resp, result)
  156. }