common/pkg/restry-pool/resty.go

83 lines
1.8 KiB
Go
Raw Normal View History

2024-05-13 19:58:26 +08:00
package restry_pool
import (
"context"
"net"
"net/http"
"sync"
"time"
2024-11-20 21:11:19 +08:00
"github.com/corpix/uarand"
"github.com/go-resty/resty/v2"
2024-05-13 19:58:26 +08:00
)
var rp *restyPool
func init() {
rp = NewRestyPool()
}
func GetRestyClient(conn net.Conn) (cli *resty.Client) {
return rp.Get(conn)
}
func PutRestyClient(cli *resty.Client) {
rp.Put(cli)
}
type restyPool struct {
resty sync.Pool
transport sync.Pool
}
const (
UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/123.0.0.0 Safari/537.36 Edg/123.0.0.0"
)
2024-05-13 21:41:26 +08:00
func beforeRequest(cli *resty.Client, req *resty.Request) error {
2024-11-29 15:45:38 +08:00
req.SetHeaders(map[string]string{
"sec-fetch-dest": "empty",
"sec-fetch-mode": "navigate",
"Accept": "*/*",
"Accept-Encoding": "gzip, deflate, br",
"Connection": "keep-alive",
"sec-fetch-site": "same-origin",
"upgrade-insecure-requests": "1",
"User-Agent": uarand.GetRandom(),
2024-11-20 21:11:19 +08:00
})
2024-05-13 21:41:26 +08:00
return nil
}
2024-05-13 19:58:26 +08:00
func NewRestyPool() *restyPool {
return &restyPool{
resty: sync.Pool{
New: func() any {
2024-06-14 15:26:27 +08:00
return resty.New().OnBeforeRequest(beforeRequest)
2024-05-13 19:58:26 +08:00
},
},
transport: sync.Pool{
New: func() any {
return &http.Transport{
MaxIdleConns: 100,
IdleConnTimeout: 90 * time.Second,
TLSHandshakeTimeout: 5 * time.Second,
}
},
},
}
}
func (r *restyPool) Get(conn net.Conn) (cli *resty.Client) {
cli = r.resty.Get().(*resty.Client)
transport := r.transport.Get().(*http.Transport)
transport.DialContext = func(ctx context.Context, network, addr string) (net.Conn, error) {
return conn, nil
}
return cli.SetTransport(transport)
}
func (r *restyPool) Put(cli *resty.Client) {
transport, _ := cli.Transport()
r.transport.Put(transport)
r.resty.Put(cli)
}