123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115 |
- package rdhttp
- import (
- "cockData/server/log"
- "cockData/server/pkg"
- "errors"
- "github.com/valyala/fasthttp"
- "github.com/valyala/fasthttp/fasthttpproxy"
- "sync"
- "time"
- )
- type ProxyResponse struct {
- Code int `json:"Code"`
- Data []struct {
- IP string `json:"IP"`
- Port string `json:"port"`
- Deadline string `json:"deadline"` // yyyy-MM-dd hh:mm:ss
- Host string `json:"host"`
- } `json:"Data"`
- Num int `json:"Num"`
- TaskID string `json:"TaskID"`
- }
- type Proxy struct {
- IP string
- Port string
- Host string
- Deadline time.Time
- UnSet bool
- }
- var lock sync.RWMutex // 读写锁
- const (
- GetProxyApi string = "https://proxy.qg.net/allocate"
- ApiKey string = "89C00D9E"
- ProxyApiSuccessCode int = 0
- )
- type GetProxyBuilder struct {
- }
- func (g GetProxyBuilder) GetParamsMap() (paramsMap map[string]string) {
- paramsMap = make(map[string]string, 0)
- paramsMap["Key"] = ApiKey
- return
- }
- func (g GetProxyBuilder) GetApiUrl() string {
- return GetProxyApi
- }
- func (g GetProxyBuilder) GetHeaders() (headers map[string]string) {
- return
- }
- var curProxy Proxy
- func GetProxy() Proxy {
- return curProxy
- }
- // OutOfTime 是否有效
- func (p *Proxy) OutOfTime() bool {
- lock.RLock()
- log.Debug("代理读锁开")
- defer func() {
- log.Debug("代理读锁关")
- lock.RUnlock()
- }()
- if p.UnSet {
- return true
- }
- if time.Now().After(p.Deadline) {
- return true
- }
- return false
- }
- func (p *Proxy) Update() error {
- lock.Lock() // 加写锁
- log.Debug("代理写锁开")
- defer func() {
- log.Debug("代理写锁关")
- lock.Unlock()
- }()
- var jsonResp ProxyResponse
- builder := GetProxyBuilder{}
- client.Dial = (&fasthttp.TCPDialer{ // 切换正常
- Concurrency: 4096,
- DNSCacheDuration: time.Hour,
- }).Dial
- err, _ := SendHttpGet(builder, &jsonResp)
- if err != nil {
- log.Warnf("更新代理失败")
- return err
- }
- if jsonResp.Code == ProxyApiSuccessCode {
- log.Infof("更新代理成功 %+v", jsonResp)
- p.IP = jsonResp.Data[0].IP
- p.Port = jsonResp.Data[0].Port
- p.Host = jsonResp.Data[0].Host
- p.Deadline = pkg.TimeParseFmt(jsonResp.Data[0].Deadline)
- p.UnSet = false
- curProxy = *p
- log.Infof("Proxy更新完毕 %s", curProxy.Host)
- // 设置client里的代理
- client.Dial = fasthttpproxy.FasthttpHTTPDialer(curProxy.Host)
- return nil
- } else {
- log.Warnf("更新代理失败 %+v", jsonResp)
- return errors.New("代理接口返回失败")
- }
- }
|