httpClient.go 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281
  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. Header: resp.Header,
  128. Body: respBody,
  129. ContentLength: resp.ContentLength,
  130. }, nil
  131. }
  132. response, err := reqFunc(nil)
  133. if err != nil {
  134. return nil, err
  135. }
  136. // 应答失败,直接返回
  137. if response.StatusCode != 200 {
  138. zap.L().Warn("[HttpGet] Response failed", zap.String("Status", response.Status), zap.String("Body", string(response.Body)))
  139. return response, fmt.Errorf("[HttpGet] Response failed")
  140. }
  141. return c.responseInterceptor(response, reqFunc), nil
  142. }
  143. // toPostBody 将任意 body 转换为 http POST 可用的 io.Reader
  144. func toPostBody(body any) (*PostBody, error) {
  145. if body == nil {
  146. return &PostBody{Reader: nil, ContentType: ""}, nil
  147. }
  148. switch v := body.(type) {
  149. case io.Reader:
  150. // 直接传 io.Reader
  151. return &PostBody{Reader: v}, nil
  152. case string:
  153. // 字符串默认 text/plain
  154. return &PostBody{Reader: strings.NewReader(v), ContentType: "text/plain"}, nil
  155. case []byte:
  156. // []byte 默认 application/octet-stream
  157. return &PostBody{Reader: bytes.NewReader(v), ContentType: "application/octet-stream"}, nil
  158. case url.Values:
  159. // 表单类型 application/x-www-form-urlencoded
  160. return &PostBody{
  161. Reader: strings.NewReader(v.Encode()),
  162. ContentType: "application/x-www-form-urlencoded; charset=UTF-8",
  163. }, nil
  164. default:
  165. // 尝试序列化为 JSON
  166. jsonData, err := json.Marshal(v)
  167. if err != nil {
  168. return nil, errors.New("unsupported body type and failed to marshal to JSON")
  169. }
  170. return &PostBody{
  171. Reader: bytes.NewReader(jsonData),
  172. ContentType: "application/json",
  173. }, nil
  174. }
  175. }
  176. func (c *HttpClient) HttpPost(url string, body any, opt *HttpClientOptions) (*Response, error) {
  177. // 转换body数据
  178. payload, err := toPostBody(body)
  179. if err != nil {
  180. zap.L().Error("to PostBody failed.", zap.String("err", err.Error()))
  181. return nil, err
  182. }
  183. zap.L().Debug("HttpPost", zap.String("url", url))
  184. // 创建请求
  185. req, err := http.NewRequest(
  186. http.MethodPost,
  187. url,
  188. payload.Reader)
  189. if err != nil {
  190. zap.L().Error("NewRequest failed.", zap.String("err", err.Error()))
  191. return nil, err
  192. }
  193. // 设置 Content-Type
  194. req.Header.Set("Content-Type", payload.ContentType)
  195. // 设置 Header
  196. if opt != nil && opt.Header != nil {
  197. for key, values := range *opt.Header {
  198. for _, v := range values {
  199. req.Header.Add(key, v)
  200. }
  201. }
  202. }
  203. // 设置 Timeout
  204. timeout := DefaultTimeout
  205. if opt != nil && opt.Timeout != nil {
  206. timeout = *opt.Timeout
  207. }
  208. // 发送请求 - 封装成函数用于重试
  209. var reqFunc = func(token *string) (*Response, error) {
  210. client := &http.Client{Timeout: timeout * time.Second}
  211. resp, err := client.Do(req)
  212. if err != nil {
  213. zap.L().Error("Do Send failed.", zap.String("err", err.Error()))
  214. return nil, err
  215. }
  216. defer resp.Body.Close()
  217. respBody, err := io.ReadAll(resp.Body)
  218. if err != nil {
  219. return nil, err
  220. }
  221. return &Response{
  222. Status: resp.Status,
  223. StatusCode: resp.StatusCode,
  224. Header: resp.Header,
  225. Body: respBody,
  226. ContentLength: resp.ContentLength,
  227. }, nil
  228. }
  229. response, err := reqFunc(nil)
  230. if err != nil {
  231. return nil, err
  232. }
  233. // 应答失败,直接返回
  234. if response.StatusCode != 200 {
  235. zap.L().Warn("[HttpPost] Response failed", zap.String("Status", response.Status), zap.String("Body", string(response.Body)))
  236. return response, fmt.Errorf("[HttpPost] Response failed")
  237. }
  238. return c.responseInterceptor(response, reqFunc), nil
  239. }