httpClient.go 6.8 KB

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