mini_facde.go 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234
  1. package facade
  2. import (
  3. "context"
  4. "encoding/json"
  5. "errors"
  6. "eta/eta_chart_lib/utils"
  7. "fmt"
  8. "io"
  9. "net/http"
  10. "strings"
  11. "sync"
  12. "time"
  13. )
  14. var (
  15. once sync.Once
  16. miniFacadeMap = make(map[string]ChartCollect)
  17. FacadeClient = BaseMiniFacade{
  18. client: DefaultClient(),
  19. }
  20. )
  21. const (
  22. bookMark = "bookMark"
  23. unBookMark = "unBookMark"
  24. )
  25. func GetInstance(name string) ChartCollect {
  26. return miniFacadeMap[name]
  27. }
  28. type ChartCollect interface {
  29. Collect(data BaseRequest) (err error)
  30. UnCollect(data BaseRequest) (err error)
  31. IsCollect(data BaseRequest) bool
  32. }
  33. type BaseRequest struct {
  34. Auth string `json:"auth"`
  35. UniqueCode string `json:"uniqueCode"`
  36. }
  37. func (bm *BaseMiniFacade) GetData() interface{} {
  38. return bm.data
  39. }
  40. func (bm *BaseMiniFacade) Post(url string, data interface{}, auth string) (result string, err error) {
  41. resp, err := bm.client.Post(url, data, auth)
  42. if err != nil {
  43. return
  44. }
  45. respBody, respErr := io.ReadAll(resp.Body)
  46. if respErr != nil {
  47. utils.FileLog.Error("读取body失败,err:%v", err)
  48. return
  49. }
  50. result = string(respBody)
  51. return
  52. }
  53. func (bm *BaseMiniFacade) Deal(data BaseRequest) *BaseMiniFacade {
  54. bm.data = data
  55. return bm
  56. }
  57. func (bm *BaseMiniFacade) HandleAction(action string, handler ChartCollect) (actionMsg string, err error) {
  58. if handler == nil {
  59. return "", errors.New("不支持的操作类型")
  60. }
  61. switch action {
  62. case bookMark:
  63. err = handler.Collect(bm.data)
  64. actionMsg = "收藏"
  65. case unBookMark:
  66. err = handler.UnCollect(bm.data)
  67. actionMsg = "取消收藏"
  68. default:
  69. err = errors.New("不支持的操作")
  70. }
  71. return
  72. }
  73. func (bm *BaseMiniFacade) IsCollect(handler ChartCollect) bool {
  74. return handler.IsCollect(bm.data)
  75. }
  76. type BaseMiniFacade struct {
  77. client *HttpClient
  78. data BaseRequest //返回参数
  79. }
  80. type HttpClient struct {
  81. *http.Client
  82. maxRetries int
  83. retryDelayFunc RetryDelayFunc
  84. }
  85. // NewClient 构造函数,其中 delayFunc 参数是可选的
  86. func NewClient(timeout time.Duration, maxRetries int, delayFunc ...RetryDelayFunc) *HttpClient {
  87. var df RetryDelayFunc
  88. if len(delayFunc) > 0 {
  89. df = delayFunc[0]
  90. } else {
  91. df = defaultRetryDelayFunc
  92. }
  93. return &HttpClient{
  94. Client: &http.Client{Timeout: timeout},
  95. maxRetries: maxRetries,
  96. retryDelayFunc: df,
  97. }
  98. }
  99. func DefaultClient() *HttpClient {
  100. return NewClient(time.Second*10, 3)
  101. }
  102. func defaultRetryDelayFunc(attempt int) time.Duration {
  103. delay := time.Duration(attempt) * time.Second
  104. if attempt > 0 {
  105. delay *= 2
  106. }
  107. return delay
  108. }
  109. type RetryDelayFunc func(attempt int) time.Duration
  110. func retryErr(err error) bool {
  111. return errors.Is(err, context.DeadlineExceeded) || errors.Is(err, context.Canceled)
  112. }
  113. // DoWithRetry 发送带有重试机制的HTTP请求,允许用户自定义重试延迟逻辑
  114. func (hc *HttpClient) DoWithRetry(ctx context.Context, req *http.Request) (resp *http.Response, err error) {
  115. attempt := 0
  116. for {
  117. resp, err = hc.Do(req.WithContext(ctx))
  118. if err != nil && retryErr(err) {
  119. if attempt >= hc.maxRetries {
  120. return nil, fmt.Errorf("请求失败: %w", err)
  121. }
  122. attempt++
  123. delay := hc.retryDelayFunc(attempt)
  124. time.Sleep(delay)
  125. continue
  126. }
  127. return
  128. }
  129. }
  130. func (hc *HttpClient) Post(url string, data interface{}, auth string) (resp *http.Response, err error) {
  131. dataStr, err := json.Marshal(data)
  132. if err != nil {
  133. utils.FileLog.Error("请求data json序列化失败,err:" + err.Error())
  134. }
  135. body := io.NopCloser(strings.NewReader(string(dataStr)))
  136. req, err := http.NewRequest(http.MethodPost, url, body)
  137. req.Header.Set("Content-Type", "application/json")
  138. req.Header.Set("Authorization", auth)
  139. if err != nil {
  140. utils.FileLog.Error("创建POST请求失败: %v", err.Error())
  141. }
  142. resp, err = hc.DoWithRetry(req.Context(), req)
  143. if err == nil {
  144. code := resp.StatusCode
  145. if code != 200 {
  146. utils.FileLog.Error("请求错误应答,状态码:%d", code)
  147. errMsg := fmt.Sprintf("请求状态码异常,StatusCode:[%d]", code)
  148. respBody, respErr := io.ReadAll(resp.Body)
  149. if respErr != nil {
  150. utils.FileLog.Error("读取body失败,err:%v", err)
  151. err = errors.New(errMsg)
  152. return
  153. }
  154. utils.FileLog.Error("请求错误应答,body:%s", string(respBody))
  155. errMsg = fmt.Sprintf("%s,body:%s", errMsg, string(respBody))
  156. err = errors.New(errMsg)
  157. return
  158. }
  159. } else {
  160. utils.FileLog.Error("未知的应答错误,获取第三方授权信息失败", err.Error())
  161. }
  162. return
  163. }
  164. func (hc *HttpClient) PostWithAuth(url string, data interface{}, token string) (resp *http.Response, err error) {
  165. dataStr, err := json.Marshal(data)
  166. if err != nil {
  167. utils.FileLog.Error("请求data json序列化失败,err:" + err.Error())
  168. }
  169. body := io.NopCloser(strings.NewReader(string(dataStr)))
  170. req, err := http.NewRequest(http.MethodPost, url, body)
  171. req.Header.Set("Content-Type", "application/json")
  172. req.Header.Set("Authorization", token)
  173. if err != nil {
  174. utils.FileLog.Error("创建POST请求失败: %v", err)
  175. }
  176. resp, err = hc.DoWithRetry(req.Context(), req)
  177. code := resp.StatusCode
  178. if code != 200 {
  179. utils.FileLog.Error("请求错误应答,状态码:%d", code)
  180. errMsg := fmt.Sprintf("请求状态码异常,StatusCode:[%d]", code)
  181. respBody, respErr := io.ReadAll(resp.Body)
  182. if respErr != nil {
  183. utils.FileLog.Error("读取body失败,err:%v", err)
  184. err = errors.New(errMsg)
  185. return
  186. }
  187. utils.FileLog.Error("请求错误应答,body:%s", string(respBody))
  188. errMsg = fmt.Sprintf("%s,body:%s", errMsg, string(respBody))
  189. err = errors.New(errMsg)
  190. return
  191. }
  192. return
  193. }
  194. func (hc *HttpClient) Get(url string) (resp *http.Response, err error) {
  195. req, err := http.NewRequestWithContext(context.Background(), http.MethodGet, url, nil)
  196. if err != nil {
  197. utils.FileLog.Error("创建请求失败: %v", err)
  198. }
  199. resp, err = hc.DoWithRetry(req.Context(), req)
  200. return
  201. }
  202. func RegisterMiniFacade(name string, facade ChartCollect) {
  203. if facade == nil {
  204. panic("实例不存在,无法注册")
  205. }
  206. if _, ok := miniFacadeMap[name]; ok {
  207. utils.FileLog.Error("请勿重复注册小程序插件:" + name)
  208. }
  209. miniFacadeMap[name] = facade
  210. }
  211. func init() {
  212. }