| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252 |
- package httpClient
- import (
- "bytes"
- "encoding/json"
- "errors"
- "io"
- "net/http"
- "net/url"
- "strings"
- "time"
- "go.uber.org/zap"
- )
- const (
- DefaultTimeout time.Duration = 5 // 默认超时时间5s
- )
- type HttpClientOptions struct {
- Timeout *time.Duration // 单位:s
- Header *http.Header
- }
- // PostBody 包含转换后的 Reader 和推荐的 Content-Type
- type PostBody struct {
- Reader io.Reader
- ContentType string
- }
- type ResponseData struct {
- Code int `json:"code"`
- }
- // 封装模块的响应结构数据
- type Response struct {
- Status string // e.g. "200 OK"
- StatusCode int // e.g. 200
- // Header maps header keys to values. If the response had multiple
- // headers with the same key, they may be concatenated, with comma
- // delimiters. (RFC 7230, section 3.2.2 requires that multiple headers
- // be semantically equivalent to a comma-delimited sequence.) When
- // Header values are duplicated by other fields in this struct (e.g.,
- // ContentLength, TransferEncoding, Trailer), the field values are
- // authoritative.
- //
- // Keys in the map are canonicalized (see CanonicalHeaderKey).
- Header http.Header
- // Body represents the response body.
- Body []byte
- // ContentLength records the length of the associated content. The
- // value -1 indicates that the length is unknown. Unless Request.Method
- // is "HEAD", values >= 0 indicate that the given number of bytes may
- // be read from Body.
- ContentLength int64
- }
- var reLogin = func() string {
- // empty function
- return ""
- }
- func responseInterceptor(response *Response, retry func(*string) (*Response, error)) *Response {
- // 判断是否回复code 401
- var data ResponseData
- if err := json.Unmarshal(response.Body, &data); err != nil {
- zap.L().Warn("ResponseData 解析失败", zap.String("body", string(response.Body)), zap.String("err", err.Error()))
- return response
- }
- if data.Code == 401 {
- tokenStr := reLogin()
- retryBody, err := retry(&tokenStr)
- if err != nil {
- zap.L().Warn("http retry 失败", zap.String("token", tokenStr), zap.String("err", err.Error()))
- return response
- }
- return retryBody
- }
- return response
- }
- func RegisterLogin(login func() string) {
- reLogin = login
- }
- func HttpGet(url string, params url.Values, opt *HttpClientOptions) (*Response, error) {
- // 拼接参数到 URL
- finalURL := url + "?" + params.Encode()
- // 创建请求
- req, err := http.NewRequest(
- http.MethodGet,
- finalURL,
- nil)
- if err != nil {
- zap.L().Error("NewRequest failed.", zap.String("err", err.Error()))
- return nil, err
- }
- // 设置 Header
- if opt != nil && opt.Header != nil {
- for key, values := range *opt.Header {
- for _, v := range values {
- req.Header.Add(key, v)
- }
- }
- }
- // 设置 Timeout
- timeout := DefaultTimeout
- if opt != nil && opt.Timeout != nil {
- timeout = *opt.Timeout
- }
- // 发送请求 - 封装成函数用于重试
- var reqFunc = func(token *string) (*Response, error) {
- client := &http.Client{Timeout: timeout * time.Second}
- resp, err := client.Do(req)
- if err != nil {
- zap.L().Error("Do Send failed.", zap.String("err", err.Error()))
- return nil, err
- }
- defer resp.Body.Close()
- respBody, err := io.ReadAll(resp.Body)
- if err != nil {
- return nil, err
- }
- return &Response{
- Status: resp.Status,
- StatusCode: resp.StatusCode,
- Body: respBody,
- ContentLength: resp.ContentLength,
- }, nil
- }
- response, err := reqFunc(nil)
- if err != nil {
- return nil, err
- }
- return responseInterceptor(response, reqFunc), nil
- }
- // toPostBody 将任意 body 转换为 http POST 可用的 io.Reader
- func toPostBody(body any) (*PostBody, error) {
- if body == nil {
- return &PostBody{Reader: nil, ContentType: ""}, nil
- }
- switch v := body.(type) {
- case io.Reader:
- // 直接传 io.Reader
- return &PostBody{Reader: v}, nil
- case string:
- // 字符串默认 text/plain
- return &PostBody{Reader: strings.NewReader(v), ContentType: "text/plain"}, nil
- case []byte:
- // []byte 默认 application/octet-stream
- return &PostBody{Reader: bytes.NewReader(v), ContentType: "application/octet-stream"}, nil
- case url.Values:
- // 表单类型 application/x-www-form-urlencoded
- return &PostBody{
- Reader: strings.NewReader(v.Encode()),
- ContentType: "application/x-www-form-urlencoded; charset=UTF-8",
- }, nil
- default:
- // 尝试序列化为 JSON
- jsonData, err := json.Marshal(v)
- if err != nil {
- return nil, errors.New("unsupported body type and failed to marshal to JSON")
- }
- return &PostBody{
- Reader: bytes.NewReader(jsonData),
- ContentType: "application/json",
- }, nil
- }
- }
- func HttpPost(url string, body any, opt *HttpClientOptions) (*Response, error) {
- // 转换body数据
- payload, err := toPostBody(body)
- if err != nil {
- zap.L().Error("to PostBody failed.", zap.String("err", err.Error()))
- return nil, err
- }
- // 创建请求
- req, err := http.NewRequest(
- http.MethodPost,
- url,
- payload.Reader)
- if err != nil {
- zap.L().Error("NewRequest failed.", zap.String("err", err.Error()))
- return nil, err
- }
- // 设置 Content-Type
- req.Header.Set("Content-Type", payload.ContentType)
- // 设置 Header
- if opt != nil && opt.Header != nil {
- for key, values := range *opt.Header {
- for _, v := range values {
- req.Header.Add(key, v)
- }
- }
- }
- // 设置 Timeout
- timeout := DefaultTimeout
- if opt != nil && opt.Timeout != nil {
- timeout = *opt.Timeout
- }
- // 发送请求 - 封装成函数用于重试
- var reqFunc = func(token *string) (*Response, error) {
- client := &http.Client{Timeout: timeout * time.Second}
- resp, err := client.Do(req)
- if err != nil {
- zap.L().Error("Do Send failed.", zap.String("err", err.Error()))
- return nil, err
- }
- defer resp.Body.Close()
- respBody, err := io.ReadAll(resp.Body)
- if err != nil {
- return nil, err
- }
- return &Response{
- Status: resp.Status,
- StatusCode: resp.StatusCode,
- Body: respBody,
- ContentLength: resp.ContentLength,
- }, nil
- }
- response, err := reqFunc(nil)
- if err != nil {
- return nil, err
- }
- return responseInterceptor(response, reqFunc), nil
- }
|