httpClient.go 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252
  1. package httpClient
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "errors"
  6. "io"
  7. "net/http"
  8. "net/url"
  9. "strings"
  10. "time"
  11. "go.uber.org/zap"
  12. )
  13. const (
  14. DefaultTimeout time.Duration = 5 // 默认超时时间5s
  15. )
  16. type HttpClientOptions struct {
  17. Timeout *time.Duration // 单位:s
  18. Header *http.Header
  19. }
  20. // PostBody 包含转换后的 Reader 和推荐的 Content-Type
  21. type PostBody struct {
  22. Reader io.Reader
  23. ContentType string
  24. }
  25. type ResponseData struct {
  26. Code int `json:"code"`
  27. }
  28. // 封装模块的响应结构数据
  29. type Response struct {
  30. Status string // e.g. "200 OK"
  31. StatusCode int // e.g. 200
  32. // Header maps header keys to values. If the response had multiple
  33. // headers with the same key, they may be concatenated, with comma
  34. // delimiters. (RFC 7230, section 3.2.2 requires that multiple headers
  35. // be semantically equivalent to a comma-delimited sequence.) When
  36. // Header values are duplicated by other fields in this struct (e.g.,
  37. // ContentLength, TransferEncoding, Trailer), the field values are
  38. // authoritative.
  39. //
  40. // Keys in the map are canonicalized (see CanonicalHeaderKey).
  41. Header http.Header
  42. // Body represents the response body.
  43. Body []byte
  44. // ContentLength records the length of the associated content. The
  45. // value -1 indicates that the length is unknown. Unless Request.Method
  46. // is "HEAD", values >= 0 indicate that the given number of bytes may
  47. // be read from Body.
  48. ContentLength int64
  49. }
  50. var reLogin = func() string {
  51. // empty function
  52. return ""
  53. }
  54. func responseInterceptor(response *Response, retry func(*string) (*Response, error)) *Response {
  55. // 判断是否回复code 401
  56. var data ResponseData
  57. if err := json.Unmarshal(response.Body, &data); err != nil {
  58. zap.L().Warn("ResponseData 解析失败", zap.String("body", string(response.Body)), zap.String("err", err.Error()))
  59. return response
  60. }
  61. if data.Code == 401 {
  62. tokenStr := reLogin()
  63. retryBody, err := retry(&tokenStr)
  64. if err != nil {
  65. zap.L().Warn("http retry 失败", zap.String("token", tokenStr), zap.String("err", err.Error()))
  66. return response
  67. }
  68. return retryBody
  69. }
  70. return response
  71. }
  72. func RegisterLogin(login func() string) {
  73. reLogin = login
  74. }
  75. func HttpGet(url string, params url.Values, opt *HttpClientOptions) (*Response, error) {
  76. // 拼接参数到 URL
  77. finalURL := url + "?" + params.Encode()
  78. // 创建请求
  79. req, err := http.NewRequest(
  80. http.MethodGet,
  81. finalURL,
  82. nil)
  83. if err != nil {
  84. zap.L().Error("NewRequest failed.", zap.String("err", err.Error()))
  85. return nil, err
  86. }
  87. // 设置 Header
  88. if opt != nil && opt.Header != nil {
  89. for key, values := range *opt.Header {
  90. for _, v := range values {
  91. req.Header.Add(key, v)
  92. }
  93. }
  94. }
  95. // 设置 Timeout
  96. timeout := DefaultTimeout
  97. if opt != nil && opt.Timeout != nil {
  98. timeout = *opt.Timeout
  99. }
  100. // 发送请求 - 封装成函数用于重试
  101. var reqFunc = func(token *string) (*Response, error) {
  102. client := &http.Client{Timeout: timeout * time.Second}
  103. resp, err := client.Do(req)
  104. if err != nil {
  105. zap.L().Error("Do Send failed.", zap.String("err", err.Error()))
  106. return nil, err
  107. }
  108. defer resp.Body.Close()
  109. respBody, err := io.ReadAll(resp.Body)
  110. if err != nil {
  111. return nil, err
  112. }
  113. return &Response{
  114. Status: resp.Status,
  115. StatusCode: resp.StatusCode,
  116. Body: respBody,
  117. ContentLength: resp.ContentLength,
  118. }, nil
  119. }
  120. response, err := reqFunc(nil)
  121. if err != nil {
  122. return nil, err
  123. }
  124. return responseInterceptor(response, reqFunc), nil
  125. }
  126. // toPostBody 将任意 body 转换为 http POST 可用的 io.Reader
  127. func toPostBody(body any) (*PostBody, error) {
  128. if body == nil {
  129. return &PostBody{Reader: nil, ContentType: ""}, nil
  130. }
  131. switch v := body.(type) {
  132. case io.Reader:
  133. // 直接传 io.Reader
  134. return &PostBody{Reader: v}, nil
  135. case string:
  136. // 字符串默认 text/plain
  137. return &PostBody{Reader: strings.NewReader(v), ContentType: "text/plain"}, nil
  138. case []byte:
  139. // []byte 默认 application/octet-stream
  140. return &PostBody{Reader: bytes.NewReader(v), ContentType: "application/octet-stream"}, nil
  141. case url.Values:
  142. // 表单类型 application/x-www-form-urlencoded
  143. return &PostBody{
  144. Reader: strings.NewReader(v.Encode()),
  145. ContentType: "application/x-www-form-urlencoded; charset=UTF-8",
  146. }, nil
  147. default:
  148. // 尝试序列化为 JSON
  149. jsonData, err := json.Marshal(v)
  150. if err != nil {
  151. return nil, errors.New("unsupported body type and failed to marshal to JSON")
  152. }
  153. return &PostBody{
  154. Reader: bytes.NewReader(jsonData),
  155. ContentType: "application/json",
  156. }, nil
  157. }
  158. }
  159. func HttpPost(url string, body any, opt *HttpClientOptions) (*Response, error) {
  160. // 转换body数据
  161. payload, err := toPostBody(body)
  162. if err != nil {
  163. zap.L().Error("to PostBody failed.", zap.String("err", err.Error()))
  164. return nil, err
  165. }
  166. // 创建请求
  167. req, err := http.NewRequest(
  168. http.MethodPost,
  169. url,
  170. payload.Reader)
  171. if err != nil {
  172. zap.L().Error("NewRequest failed.", zap.String("err", err.Error()))
  173. return nil, err
  174. }
  175. // 设置 Content-Type
  176. req.Header.Set("Content-Type", payload.ContentType)
  177. // 设置 Header
  178. if opt != nil && opt.Header != nil {
  179. for key, values := range *opt.Header {
  180. for _, v := range values {
  181. req.Header.Add(key, v)
  182. }
  183. }
  184. }
  185. // 设置 Timeout
  186. timeout := DefaultTimeout
  187. if opt != nil && opt.Timeout != nil {
  188. timeout = *opt.Timeout
  189. }
  190. // 发送请求 - 封装成函数用于重试
  191. var reqFunc = func(token *string) (*Response, error) {
  192. client := &http.Client{Timeout: timeout * time.Second}
  193. resp, err := client.Do(req)
  194. if err != nil {
  195. zap.L().Error("Do Send failed.", zap.String("err", err.Error()))
  196. return nil, err
  197. }
  198. defer resp.Body.Close()
  199. respBody, err := io.ReadAll(resp.Body)
  200. if err != nil {
  201. return nil, err
  202. }
  203. return &Response{
  204. Status: resp.Status,
  205. StatusCode: resp.StatusCode,
  206. Body: respBody,
  207. ContentLength: resp.ContentLength,
  208. }, nil
  209. }
  210. response, err := reqFunc(nil)
  211. if err != nil {
  212. return nil, err
  213. }
  214. return responseInterceptor(response, reqFunc), nil
  215. }