102 lines
2.5 KiB
Go
102 lines
2.5 KiB
Go
// Package restyclient for http client
|
||
package restyclient
|
||
|
||
import (
|
||
"context"
|
||
"crypto/tls"
|
||
"net"
|
||
"net/http"
|
||
"sync"
|
||
"time"
|
||
|
||
"github.com/go-resty/resty/v2"
|
||
"github.com/google/uuid"
|
||
"go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp"
|
||
)
|
||
|
||
const (
|
||
timeout = time.Second * 30
|
||
)
|
||
|
||
var (
|
||
clientOnce sync.Once
|
||
silentClientOnce sync.Once
|
||
globalClient *resty.Client
|
||
globalSilentClient *resty.Client
|
||
)
|
||
|
||
var dialer = &net.Dialer{
|
||
Timeout: 30 * time.Second,
|
||
KeepAlive: 30 * time.Second,
|
||
}
|
||
|
||
// defaultTransport default transport
|
||
var defaultTransport http.RoundTripper = &http.Transport{
|
||
DialContext: dialer.DialContext,
|
||
ForceAttemptHTTP2: true,
|
||
MaxIdleConns: 100,
|
||
IdleConnTimeout: 90 * time.Second,
|
||
TLSHandshakeTimeout: 10 * time.Second,
|
||
ExpectContinueTimeout: 1 * time.Second,
|
||
// NOCC:gas/tls(设计如此)
|
||
TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, // nolint
|
||
}
|
||
|
||
// New : 新建 Client, 设置公共参数,tracing 等; 每次新建,cookies不复用
|
||
func New() *resty.Client {
|
||
if globalClient == nil {
|
||
clientOnce.Do(func() {
|
||
globalClient = resty.New().
|
||
SetTransport(otelhttp.NewTransport(defaultTransport)).
|
||
SetTimeout(timeout).
|
||
SetCookieJar(nil).
|
||
SetDebugBodyLimit(1024).
|
||
OnAfterResponse(restyAfterResponseHook).
|
||
SetPreRequestHook(restyBeforeRequestHook).
|
||
OnError(restyErrHook).
|
||
SetHeader("User-Agent", "restyclient")
|
||
})
|
||
}
|
||
return globalClient
|
||
}
|
||
|
||
// silentNew 安静模式,只打印错误日志
|
||
func silentNew() *resty.Client {
|
||
if globalSilentClient == nil {
|
||
silentClientOnce.Do(func() {
|
||
globalSilentClient = resty.New().
|
||
SetTransport(otelhttp.NewTransport(defaultTransport)).
|
||
SetTimeout(timeout).
|
||
SetCookieJar(nil).
|
||
SetDebugBodyLimit(1024).
|
||
// OnAfterResponse(restyAfterResponseHook).
|
||
// SetPreRequestHook(restyBeforeRequestHook).
|
||
OnError(restyErrHook).
|
||
SetHeader("User-Agent", "envmgr-restyclient")
|
||
})
|
||
}
|
||
return globalSilentClient
|
||
}
|
||
|
||
// R : New().R() 快捷方式, 已设置公共参数,tracing 等
|
||
func R() *resty.Request {
|
||
return New().R()
|
||
}
|
||
|
||
// SilentR : 安静模式,只打印错误日志 已设置公共参数,tracing 等, 只打印错误日志
|
||
func SilentR() *resty.Request {
|
||
return silentNew().R()
|
||
}
|
||
|
||
// GenRequestID 生产 request_id
|
||
func GenRequestID() string {
|
||
id, _ := uuid.NewRandom()
|
||
return id.String()
|
||
}
|
||
|
||
// WithRequestID 设置 request_id
|
||
func WithRequestID(ctx context.Context, id string) context.Context {
|
||
newCtx := context.WithValue(ctx, requestIDCtxKey, id)
|
||
return newCtx
|
||
}
|