httpClient.go 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283
  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. // TODO 调整401判断逻辑,待观察是否有问题
  67. if response.StatusCode == 401 {
  68. if c.reLogin == nil {
  69. return response
  70. }
  71. tokenStr := (*c.reLogin)()
  72. retryBody, err := retry(&tokenStr)
  73. if err != nil {
  74. zap.L().Warn("http retry 失败", zap.String("token", tokenStr), zap.String("err", err.Error()))
  75. return response
  76. }
  77. return retryBody
  78. }
  79. return response
  80. }
  81. func (c *HttpClient) RegisterLogin(login func() string) {
  82. c.reLogin = &login
  83. }
  84. func (c *HttpClient) HttpGet(url string, params *url.Values, opt *HttpClientOptions) (*Response, error) {
  85. // 拼接参数到 URL
  86. finalURL := url
  87. if params != nil {
  88. finalURL = finalURL + "?" + params.Encode()
  89. }
  90. zap.L().Debug("HttpGet", zap.String("url", finalURL))
  91. // 创建请求
  92. req, err := http.NewRequest(
  93. http.MethodGet,
  94. finalURL,
  95. nil)
  96. if err != nil {
  97. zap.L().Error("NewRequest failed.", zap.String("err", err.Error()))
  98. return nil, err
  99. }
  100. // 设置 Header
  101. if opt != nil && opt.Header != nil {
  102. for key, values := range *opt.Header {
  103. for _, v := range values {
  104. req.Header.Add(key, v)
  105. }
  106. }
  107. }
  108. // 设置 Timeout
  109. timeout := DefaultTimeout
  110. if opt != nil && opt.Timeout != nil {
  111. timeout = *opt.Timeout
  112. }
  113. // 发送请求 - 封装成函数用于重试
  114. var reqFunc = func(token *string) (*Response, error) {
  115. client := &http.Client{Timeout: timeout * time.Second}
  116. resp, err := client.Do(req)
  117. if err != nil {
  118. zap.L().Error("Do Send failed.", zap.String("err", err.Error()))
  119. return nil, err
  120. }
  121. defer resp.Body.Close()
  122. respBody, err := io.ReadAll(resp.Body)
  123. if err != nil {
  124. return nil, err
  125. }
  126. return &Response{
  127. Status: resp.Status,
  128. StatusCode: resp.StatusCode,
  129. Header: resp.Header,
  130. Body: respBody,
  131. ContentLength: resp.ContentLength,
  132. }, nil
  133. }
  134. response, err := reqFunc(nil)
  135. if err != nil {
  136. return nil, err
  137. }
  138. // 应答失败,直接返回
  139. if response.StatusCode != 200 {
  140. zap.L().Warn("[HttpGet] Response failed", zap.String("Status", response.Status), zap.String("Body", string(response.Body)))
  141. return response, fmt.Errorf("[HttpGet] Response failed")
  142. }
  143. return c.responseInterceptor(response, reqFunc), nil
  144. }
  145. // toPostBody 将任意 body 转换为 http POST 可用的 io.Reader
  146. func toPostBody(body any) (*PostBody, error) {
  147. if body == nil {
  148. return &PostBody{Reader: nil, ContentType: ""}, nil
  149. }
  150. switch v := body.(type) {
  151. case io.Reader:
  152. // 直接传 io.Reader
  153. return &PostBody{Reader: v}, nil
  154. case string:
  155. // 字符串默认 text/plain
  156. return &PostBody{Reader: strings.NewReader(v), ContentType: "text/plain"}, nil
  157. case []byte:
  158. // []byte 默认 application/octet-stream
  159. return &PostBody{Reader: bytes.NewReader(v), ContentType: "application/octet-stream"}, nil
  160. case url.Values:
  161. // 表单类型 application/x-www-form-urlencoded
  162. return &PostBody{
  163. Reader: strings.NewReader(v.Encode()),
  164. ContentType: "application/x-www-form-urlencoded; charset=UTF-8",
  165. }, nil
  166. default:
  167. // 尝试序列化为 JSON
  168. jsonData, err := json.Marshal(v)
  169. if err != nil {
  170. return nil, errors.New("unsupported body type and failed to marshal to JSON")
  171. }
  172. return &PostBody{
  173. Reader: bytes.NewReader(jsonData),
  174. ContentType: "application/json",
  175. }, nil
  176. }
  177. }
  178. func (c *HttpClient) HttpPost(url string, body any, opt *HttpClientOptions) (*Response, error) {
  179. // 转换body数据
  180. payload, err := toPostBody(body)
  181. if err != nil {
  182. zap.L().Error("to PostBody failed.", zap.String("err", err.Error()))
  183. return nil, err
  184. }
  185. zap.L().Debug("HttpPost", zap.String("url", url))
  186. // 创建请求
  187. req, err := http.NewRequest(
  188. http.MethodPost,
  189. url,
  190. payload.Reader)
  191. if err != nil {
  192. zap.L().Error("NewRequest failed.", zap.String("err", err.Error()))
  193. return nil, err
  194. }
  195. // 设置 Content-Type
  196. req.Header.Set("Content-Type", payload.ContentType)
  197. // 设置 Header
  198. if opt != nil && opt.Header != nil {
  199. for key, values := range *opt.Header {
  200. for _, v := range values {
  201. req.Header.Add(key, v)
  202. }
  203. }
  204. }
  205. // 设置 Timeout
  206. timeout := DefaultTimeout
  207. if opt != nil && opt.Timeout != nil {
  208. timeout = *opt.Timeout
  209. }
  210. // 发送请求 - 封装成函数用于重试
  211. var reqFunc = func(token *string) (*Response, error) {
  212. client := &http.Client{Timeout: timeout * time.Second}
  213. resp, err := client.Do(req)
  214. if err != nil {
  215. zap.L().Error("Do Send failed.", zap.String("err", err.Error()))
  216. return nil, err
  217. }
  218. defer resp.Body.Close()
  219. respBody, err := io.ReadAll(resp.Body)
  220. if err != nil {
  221. return nil, err
  222. }
  223. return &Response{
  224. Status: resp.Status,
  225. StatusCode: resp.StatusCode,
  226. Header: resp.Header,
  227. Body: respBody,
  228. ContentLength: resp.ContentLength,
  229. }, nil
  230. }
  231. response, err := reqFunc(nil)
  232. if err != nil {
  233. return nil, err
  234. }
  235. // 应答失败,直接返回
  236. if response.StatusCode != 200 {
  237. zap.L().Warn("[HttpPost] Response failed", zap.String("Status", response.Status), zap.String("Body", string(response.Body)))
  238. return response, fmt.Errorf("[HttpPost] Response failed")
  239. }
  240. return c.responseInterceptor(response, reqFunc), nil
  241. }