proxy.go 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115
  1. package rdhttp
  2. import (
  3. "cockData/server/log"
  4. "cockData/server/pkg"
  5. "errors"
  6. "github.com/valyala/fasthttp"
  7. "github.com/valyala/fasthttp/fasthttpproxy"
  8. "sync"
  9. "time"
  10. )
  11. type ProxyResponse struct {
  12. Code int `json:"Code"`
  13. Data []struct {
  14. IP string `json:"IP"`
  15. Port string `json:"port"`
  16. Deadline string `json:"deadline"` // yyyy-MM-dd hh:mm:ss
  17. Host string `json:"host"`
  18. } `json:"Data"`
  19. Num int `json:"Num"`
  20. TaskID string `json:"TaskID"`
  21. }
  22. type Proxy struct {
  23. IP string
  24. Port string
  25. Host string
  26. Deadline time.Time
  27. UnSet bool
  28. }
  29. var lock sync.RWMutex // 读写锁
  30. const (
  31. GetProxyApi string = "https://proxy.qg.net/allocate"
  32. ApiKey string = "89C00D9E"
  33. ProxyApiSuccessCode int = 0
  34. )
  35. type GetProxyBuilder struct {
  36. }
  37. func (g GetProxyBuilder) GetParamsMap() (paramsMap map[string]string) {
  38. paramsMap = make(map[string]string, 0)
  39. paramsMap["Key"] = ApiKey
  40. return
  41. }
  42. func (g GetProxyBuilder) GetApiUrl() string {
  43. return GetProxyApi
  44. }
  45. func (g GetProxyBuilder) GetHeaders() (headers map[string]string) {
  46. return
  47. }
  48. var curProxy Proxy
  49. func GetProxy() Proxy {
  50. return curProxy
  51. }
  52. // OutOfTime 是否有效
  53. func (p *Proxy) OutOfTime() bool {
  54. lock.RLock()
  55. log.Debug("代理读锁开")
  56. defer func() {
  57. log.Debug("代理读锁关")
  58. lock.RUnlock()
  59. }()
  60. if p.UnSet {
  61. return true
  62. }
  63. if time.Now().After(p.Deadline) {
  64. return true
  65. }
  66. return false
  67. }
  68. func (p *Proxy) Update() error {
  69. lock.Lock() // 加写锁
  70. log.Debug("代理写锁开")
  71. defer func() {
  72. log.Debug("代理写锁关")
  73. lock.Unlock()
  74. }()
  75. var jsonResp ProxyResponse
  76. builder := GetProxyBuilder{}
  77. client.Dial = (&fasthttp.TCPDialer{ // 切换正常
  78. Concurrency: 4096,
  79. DNSCacheDuration: time.Hour,
  80. }).Dial
  81. err, _ := SendHttpGet(builder, &jsonResp)
  82. if err != nil {
  83. log.Warnf("更新代理失败")
  84. return err
  85. }
  86. if jsonResp.Code == ProxyApiSuccessCode {
  87. log.Infof("更新代理成功 %+v", jsonResp)
  88. p.IP = jsonResp.Data[0].IP
  89. p.Port = jsonResp.Data[0].Port
  90. p.Host = jsonResp.Data[0].Host
  91. p.Deadline = pkg.TimeParseFmt(jsonResp.Data[0].Deadline)
  92. p.UnSet = false
  93. curProxy = *p
  94. log.Infof("Proxy更新完毕 %s", curProxy.Host)
  95. // 设置client里的代理
  96. client.Dial = fasthttpproxy.FasthttpHTTPDialer(curProxy.Host)
  97. return nil
  98. } else {
  99. log.Warnf("更新代理失败 %+v", jsonResp)
  100. return errors.New("代理接口返回失败")
  101. }
  102. }