option.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121
  1. package httpclient
  2. import (
  3. "sync"
  4. "time"
  5. "git.bvbej.com/bvbej/base-golang/pkg/trace"
  6. "go.uber.org/zap"
  7. )
  8. var (
  9. cache = &sync.Pool{
  10. New: func() interface{} {
  11. return &option{
  12. header: make(map[string][]string),
  13. }
  14. },
  15. }
  16. )
  17. // Mock 定义接口Mock数据
  18. type Mock func() (body []byte)
  19. // Option 自定义设置http请求
  20. type Option func(*option)
  21. type option struct {
  22. ttl time.Duration
  23. header map[string][]string
  24. trace *trace.Trace
  25. dialog *trace.Dialog
  26. logger *zap.Logger
  27. retryTimes int
  28. retryDelay time.Duration
  29. retryVerify RetryVerify
  30. alarmTitle string
  31. alarmObject AlarmObject
  32. alarmVerify AlarmVerify
  33. mock Mock
  34. }
  35. func (o *option) reset() {
  36. o.ttl = 0
  37. o.header = make(map[string][]string)
  38. o.trace = nil
  39. o.dialog = nil
  40. o.logger = nil
  41. o.retryTimes = 0
  42. o.retryDelay = 0
  43. o.retryVerify = nil
  44. o.alarmTitle = ""
  45. o.alarmObject = nil
  46. o.alarmVerify = nil
  47. o.mock = nil
  48. }
  49. func getOption() *option {
  50. return cache.Get().(*option)
  51. }
  52. func releaseOption(opt *option) {
  53. opt.reset()
  54. cache.Put(opt)
  55. }
  56. // WithTTL 本次http请求最长执行时间
  57. func WithTTL(ttl time.Duration) Option {
  58. return func(opt *option) {
  59. opt.ttl = ttl
  60. }
  61. }
  62. // WithHeader 设置http header,可以调用多次设置多对key-value
  63. func WithHeader(key, value string) Option {
  64. return func(opt *option) {
  65. opt.header[key] = []string{value}
  66. }
  67. }
  68. // WithTrace 设置trace信息
  69. func WithTrace(t trace.T) Option {
  70. return func(opt *option) {
  71. if t != nil {
  72. opt.trace = t.(*trace.Trace)
  73. opt.dialog = new(trace.Dialog)
  74. }
  75. }
  76. }
  77. // WithLogger 设置logger以便打印关键日志
  78. func WithLogger(logger *zap.Logger) Option {
  79. return func(opt *option) {
  80. opt.logger = logger
  81. }
  82. }
  83. // WithMock 设置 mock 数据
  84. func WithMock(m Mock) Option {
  85. return func(opt *option) {
  86. opt.mock = m
  87. }
  88. }
  89. // WithOnFailedAlarm 设置告警通知
  90. func WithOnFailedAlarm(alarmTitle string, alarmObject AlarmObject, alarmVerify AlarmVerify) Option {
  91. return func(opt *option) {
  92. opt.alarmTitle = alarmTitle
  93. opt.alarmObject = alarmObject
  94. opt.alarmVerify = alarmVerify
  95. }
  96. }
  97. // WithOnFailedRetry 设置失败重试
  98. func WithOnFailedRetry(retryTimes int, retryDelay time.Duration, retryVerify RetryVerify) Option {
  99. return func(opt *option) {
  100. opt.retryTimes = retryTimes
  101. opt.retryDelay = retryDelay
  102. opt.retryVerify = retryVerify
  103. }
  104. }