httpClient.go 6.6 KB

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