-
Notifications
You must be signed in to change notification settings - Fork 0
/
resty.go
84 lines (72 loc) · 1.66 KB
/
resty.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
package resty
import (
"net"
"net/http"
"net/http/cookiejar"
"os"
"runtime"
"strconv"
"sync"
"time"
"github.com/go-resty/resty/v2"
"golang.org/x/net/publicsuffix"
"github.com/starudream/go-lib/core/v2/codec/json"
"github.com/starudream/go-lib/core/v2/utils/osutil"
)
type (
Client = resty.Client
Request = resty.Request
Response = resty.Response
)
func New() *Client {
c := newClient()
c.SetDisableWarn(true)
c.SetLogger(_logger)
c.SetDebug(debug())
c.SetDebugBodyLimit(1 << 16) // 65536
c.SetJSONMarshaler(json.Marshal)
c.SetJSONUnmarshaler(json.Unmarshal)
c.SetHeader(HeaderUserAgent, runtime.Version())
return c
}
var (
_c *Client
_cOnce sync.Once
)
func C() *Client {
_cOnce.Do(func() { _c = New() })
return _c
}
func R(rOptions ...ROption) *Request {
opts := newROptions(rOptions...)
return C().R().SetHeaders(opts.Headers)
}
func newClient() *Client {
cookieJar, _ := cookiejar.New(&cookiejar.Options{PublicSuffixList: publicsuffix.List})
return resty.NewWithClient(&http.Client{Transport: createTransport(), Jar: cookieJar})
}
func createTransport() *http.Transport {
return &http.Transport{
Proxy: http.ProxyFromEnvironment,
DialContext: (&net.Dialer{
Timeout: 30 * time.Second,
KeepAlive: 30 * time.Second,
}).DialContext,
ForceAttemptHTTP2: true,
MaxIdleConns: 100,
IdleConnTimeout: 90 * time.Second,
TLSHandshakeTimeout: 10 * time.Second,
ExpectContinueTimeout: 1 * time.Second,
MaxIdleConnsPerHost: runtime.GOMAXPROCS(0) + 1,
}
}
func debug() bool {
v := osutil.DOT()
if s := os.Getenv("RESTY_DEBUG"); s != "" {
t, e := strconv.ParseBool(s)
if e == nil {
v = t
}
}
return v
}