httpClient.go 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337
  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 失败(401 重新登录后重试)",
  75. zap.Int("tokenLen", len(tokenStr)), // 避免明文记录 token,仅记录长度
  76. zap.Int("originStatusCode", response.StatusCode),
  77. zap.String("err", err.Error()),
  78. )
  79. return response
  80. }
  81. return retryBody
  82. }
  83. return response
  84. }
  85. func (c *HttpClient) RegisterLogin(login func() string) {
  86. c.reLogin = &login
  87. }
  88. func (c *HttpClient) HttpGet(url string, params *url.Values, opt *HttpClientOptions) (*Response, error) {
  89. // 拼接参数到 URL
  90. finalURL := url
  91. if params != nil {
  92. finalURL = finalURL + "?" + params.Encode()
  93. }
  94. zap.L().Debug("HttpGet", zap.String("url", finalURL))
  95. // 创建请求
  96. req, err := http.NewRequest(
  97. http.MethodGet,
  98. finalURL,
  99. nil)
  100. if err != nil {
  101. zap.L().Error("[HttpGet] NewRequest failed.",
  102. zap.String("method", http.MethodGet),
  103. zap.String("url", finalURL),
  104. zap.String("err", err.Error()),
  105. )
  106. return nil, err
  107. }
  108. // 设置 Header
  109. if opt != nil && opt.Header != nil {
  110. for key, values := range *opt.Header {
  111. for _, v := range values {
  112. req.Header.Add(key, v)
  113. }
  114. }
  115. }
  116. // 设置 Timeout
  117. timeout := DefaultTimeout
  118. if opt != nil && opt.Timeout != nil {
  119. timeout = *opt.Timeout
  120. }
  121. // 发送请求 - 封装成函数用于重试
  122. var reqFunc = func(token *string) (*Response, error) {
  123. client := &http.Client{Timeout: timeout * time.Second}
  124. resp, err := client.Do(req)
  125. if err != nil {
  126. zap.L().Error("[HttpGet] Do Send failed.",
  127. zap.String("method", http.MethodGet),
  128. zap.String("url", finalURL),
  129. zap.Duration("timeout", timeout*time.Second),
  130. zap.String("err", err.Error()),
  131. )
  132. return nil, err
  133. }
  134. defer resp.Body.Close()
  135. respBody, err := io.ReadAll(resp.Body)
  136. if err != nil {
  137. zap.L().Error("[HttpGet] Read response body failed.",
  138. zap.String("method", http.MethodGet),
  139. zap.String("url", finalURL),
  140. zap.String("status", resp.Status),
  141. zap.String("err", err.Error()),
  142. )
  143. return nil, err
  144. }
  145. return &Response{
  146. Status: resp.Status,
  147. StatusCode: resp.StatusCode,
  148. Header: resp.Header,
  149. Body: respBody,
  150. ContentLength: resp.ContentLength,
  151. }, nil
  152. }
  153. response, err := reqFunc(nil)
  154. if err != nil {
  155. return nil, err
  156. }
  157. // 应答失败,直接返回
  158. if response.StatusCode != 200 {
  159. zap.L().Warn("[HttpGet] Response failed",
  160. zap.String("method", http.MethodGet),
  161. zap.String("url", finalURL),
  162. zap.String("status", response.Status),
  163. zap.Int("statusCode", response.StatusCode),
  164. zap.String("body", string(response.Body)),
  165. )
  166. return response, fmt.Errorf("[HttpGet] Response failed, url=%s, status=%s", finalURL, response.Status)
  167. }
  168. return c.responseInterceptor(response, reqFunc), nil
  169. }
  170. // toPostBody 将任意 body 转换为 http POST 可用的 io.Reader
  171. func toPostBody(body any) (*PostBody, error) {
  172. if body == nil {
  173. return &PostBody{Reader: nil, ContentType: ""}, nil
  174. }
  175. switch v := body.(type) {
  176. case io.Reader:
  177. // 直接传 io.Reader
  178. return &PostBody{Reader: v}, nil
  179. case string:
  180. // 字符串默认 text/plain
  181. return &PostBody{Reader: strings.NewReader(v), ContentType: "text/plain"}, nil
  182. case []byte:
  183. // []byte 默认 application/octet-stream
  184. return &PostBody{Reader: bytes.NewReader(v), ContentType: "application/octet-stream"}, nil
  185. case url.Values:
  186. // 表单类型 application/x-www-form-urlencoded
  187. return &PostBody{
  188. Reader: strings.NewReader(v.Encode()),
  189. ContentType: "application/x-www-form-urlencoded; charset=UTF-8",
  190. }, nil
  191. default:
  192. // 尝试序列化为 JSON
  193. jsonData, err := json.Marshal(v)
  194. if err != nil {
  195. return nil, errors.New("unsupported body type and failed to marshal to JSON")
  196. }
  197. return &PostBody{
  198. Reader: bytes.NewReader(jsonData),
  199. ContentType: "application/json",
  200. }, nil
  201. }
  202. }
  203. func (c *HttpClient) HttpPost(url string, body any, opt *HttpClientOptions) (*Response, error) {
  204. // 转换body数据
  205. payload, err := toPostBody(body)
  206. if err != nil {
  207. zap.L().Error("[HttpPost] to PostBody failed.",
  208. zap.String("method", http.MethodPost),
  209. zap.String("url", url),
  210. zap.String("bodyType", fmt.Sprintf("%T", body)),
  211. zap.String("err", err.Error()),
  212. )
  213. return nil, err
  214. }
  215. zap.L().Debug("HttpPost", zap.String("url", url), zap.String("contentType", payload.ContentType))
  216. // 创建请求
  217. req, err := http.NewRequest(
  218. http.MethodPost,
  219. url,
  220. payload.Reader)
  221. if err != nil {
  222. zap.L().Error("[HttpPost] NewRequest failed.",
  223. zap.String("method", http.MethodPost),
  224. zap.String("url", url),
  225. zap.String("contentType", payload.ContentType),
  226. zap.String("err", err.Error()),
  227. )
  228. return nil, err
  229. }
  230. // 设置 Content-Type
  231. req.Header.Set("Content-Type", payload.ContentType)
  232. // 设置 Header
  233. if opt != nil && opt.Header != nil {
  234. for key, values := range *opt.Header {
  235. for _, v := range values {
  236. req.Header.Add(key, v)
  237. }
  238. }
  239. }
  240. // 设置 Timeout
  241. timeout := DefaultTimeout
  242. if opt != nil && opt.Timeout != nil {
  243. timeout = *opt.Timeout
  244. }
  245. // 发送请求 - 封装成函数用于重试
  246. var reqFunc = func(token *string) (*Response, error) {
  247. client := &http.Client{Timeout: timeout * time.Second}
  248. resp, err := client.Do(req)
  249. if err != nil {
  250. zap.L().Error("[HttpPost] Do Send failed.",
  251. zap.String("method", http.MethodPost),
  252. zap.String("url", url),
  253. zap.String("contentType", payload.ContentType),
  254. zap.Duration("timeout", timeout*time.Second),
  255. zap.String("err", err.Error()),
  256. )
  257. return nil, err
  258. }
  259. defer resp.Body.Close()
  260. respBody, err := io.ReadAll(resp.Body)
  261. if err != nil {
  262. zap.L().Error("[HttpPost] Read response body failed.",
  263. zap.String("method", http.MethodPost),
  264. zap.String("url", url),
  265. zap.String("status", resp.Status),
  266. zap.String("err", err.Error()),
  267. )
  268. return nil, err
  269. }
  270. return &Response{
  271. Status: resp.Status,
  272. StatusCode: resp.StatusCode,
  273. Header: resp.Header,
  274. Body: respBody,
  275. ContentLength: resp.ContentLength,
  276. }, nil
  277. }
  278. response, err := reqFunc(nil)
  279. if err != nil {
  280. return nil, err
  281. }
  282. // 应答失败,直接返回
  283. if response.StatusCode != 200 {
  284. zap.L().Warn("[HttpPost] Response failed",
  285. zap.String("method", http.MethodPost),
  286. zap.String("url", url),
  287. zap.String("contentType", payload.ContentType),
  288. zap.String("status", response.Status),
  289. zap.Int("statusCode", response.StatusCode),
  290. zap.String("body", string(response.Body)),
  291. )
  292. return response, fmt.Errorf("[HttpPost] Response failed, url=%s, status=%s", url, response.Status)
  293. }
  294. return c.responseInterceptor(response, reqFunc), nil
  295. }