common/pkg/coach-client/client.go

65 lines
1.6 KiB
Go

package coach_client
import (
"context"
"fmt"
"gitea.timerzz.com/kedaya_haitao/common/pkg/proxy"
restry_pool "gitea.timerzz.com/kedaya_haitao/common/pkg/restry-pool"
"github.com/go-resty/resty/v2"
"github.com/pkg/errors"
proxy2 "github.com/timerzz/proxypool/pkg/proxy"
"log/slog"
"time"
)
type Client struct {
pool *proxy.ProxyPool
defaultTimeOut time.Duration
}
func NewClient(pool *proxy.ProxyPool) *Client {
return &Client{
pool: pool,
defaultTimeOut: 10 * time.Minute,
}
}
func tryRequest(ctx context.Context, urlPath string, respData any, proxyGetter func() proxy2.Proxy) error {
for p := proxyGetter(); p != nil; p = proxyGetter() {
select {
case <-ctx.Done():
if errors.Is(ctx.Err(), context.DeadlineExceeded) {
return fmt.Errorf("超时未获取到结果,链接:%s", urlPath)
}
return nil
default:
}
_, err := callByProxy(ctx, p, urlPath, respData)
if err != nil {
slog.Debug(err.Error())
continue
}
return nil
}
return errors.New("未获取到可用的代理")
}
func callByProxy(ctx context.Context, p proxy2.Proxy, urlPath string, result any) (*resty.Response, error) {
addr, err := proxy.UrlToMetadata(urlPath)
if err != nil {
return nil, err
}
subCtx, cancel := context.WithTimeout(ctx, time.Second*10)
defer cancel()
conn, err := proxy.ConnFromProxy(subCtx, p, addr)
if err != nil {
return nil, errors.Wrap(err, "创建conn失败")
}
defer conn.Close()
var cli = restry_pool.GetRestyClient(conn)
defer restry_pool.PutRestyClient(cli)
return cli.R().SetResult(result).Get(urlPath)
}