network_client.go 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188
  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: 30 * 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. println("Header====>>>>", req.Header)
  51. return c.client.Do(req)
  52. }
  53. // Post 发起POST请求
  54. func (c *HTTPClient) Post(ctx context.Context, endpoint string, data interface{}, headers map[string]string) (*http.Response, error) {
  55. url := c.baseURL + endpoint
  56. var reqBody io.Reader
  57. if data != nil {
  58. jsonData, err := json.Marshal(data)
  59. if err != nil {
  60. return nil, fmt.Errorf("序列化请求数据失败: %w", err)
  61. }
  62. reqBody = bytes.NewBuffer(jsonData)
  63. }
  64. req, err := http.NewRequestWithContext(ctx, "POST", url, reqBody)
  65. if err != nil {
  66. return nil, fmt.Errorf("创建请求失败: %w", err)
  67. }
  68. // 设置默认headers
  69. req.Header.Set("Content-Type", "application/json")
  70. if c.Authorization != "" {
  71. req.Header.Set("Authorization", "Bearer "+c.Authorization)
  72. }
  73. // 设置自定义headers
  74. for key, value := range headers {
  75. req.Header.Set(key, value)
  76. }
  77. return c.client.Do(req)
  78. }
  79. // UploadFile 上传文件
  80. func (c *HTTPClient) UploadFile(ctx context.Context, endpoint string, filePath string, fieldName string, headers map[string]string, result interface{}) error {
  81. url := c.baseURL + endpoint
  82. // 打开文件
  83. file, err := os.Open(filePath)
  84. if err != nil {
  85. return fmt.Errorf("打开文件失败: %w", err)
  86. }
  87. defer file.Close()
  88. // 创建multipart表单
  89. var buf bytes.Buffer
  90. writer := multipart.NewWriter(&buf)
  91. // 添加文件字段
  92. fileWriter, err := writer.CreateFormFile(fieldName, filepath.Base(filePath))
  93. if err != nil {
  94. return fmt.Errorf("创建表单文件字段失败: %w", err)
  95. }
  96. // 复制文件内容到表单
  97. _, err = io.Copy(fileWriter, file)
  98. if err != nil {
  99. return fmt.Errorf("复制文件内容失败: %w", err)
  100. }
  101. // 关闭表单写入器
  102. err = writer.Close()
  103. if err != nil {
  104. return fmt.Errorf("关闭表单写入器失败: %w", err)
  105. }
  106. // 创建请求
  107. req, err := http.NewRequestWithContext(ctx, "POST", url, &buf)
  108. if err != nil {
  109. return fmt.Errorf("创建请求失败: %w", err)
  110. }
  111. // 设置内容类型为multipart表单
  112. req.Header.Set("Content-Type", writer.FormDataContentType())
  113. // 设置认证头
  114. if c.Authorization != "" {
  115. req.Header.Set("Authorization", "Bearer "+c.Authorization)
  116. }
  117. // 设置自定义headers
  118. for key, value := range headers {
  119. req.Header.Set(key, value)
  120. }
  121. resp, err := c.client.Do(req)
  122. if err != nil {
  123. return err
  124. }
  125. return c.ParseJSON(resp, result)
  126. }
  127. // ParseJSON 解析JSON响应
  128. func (c *HTTPClient) ParseJSON(resp *http.Response, result interface{}) error {
  129. defer resp.Body.Close()
  130. body, err := io.ReadAll(resp.Body)
  131. if err != nil {
  132. return fmt.Errorf("读取响应体失败: %w", err)
  133. }
  134. if resp.StatusCode >= 400 {
  135. return fmt.Errorf("请求失败 status=%d body=%s", resp.StatusCode, string(body))
  136. }
  137. if err := json.Unmarshal(body, result); err != nil {
  138. return fmt.Errorf("解析JSON失败: %w, body=%s", err, string(body))
  139. }
  140. return nil
  141. }
  142. // GetJSON 发起GET请求并解析JSON响应
  143. func (c *HTTPClient) GetJSON(ctx context.Context, endpoint string, result interface{}, headers map[string]string) error {
  144. resp, err := c.Get(ctx, endpoint, headers)
  145. if err != nil {
  146. return err
  147. }
  148. return c.ParseJSON(resp, result)
  149. }
  150. // PostJSON 发起POST请求并解析JSON响应
  151. func (c *HTTPClient) PostJSON(ctx context.Context, endpoint string, data interface{}, result interface{}, headers map[string]string) error {
  152. resp, err := c.Post(ctx, endpoint, data, headers)
  153. if err != nil {
  154. return err
  155. }
  156. return c.ParseJSON(resp, result)
  157. }