-
Notifications
You must be signed in to change notification settings - Fork 0
/
httpclient.go
62 lines (52 loc) · 1.21 KB
/
httpclient.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
// Copyright (c) Mondoo, Inc.
// SPDX-License-Identifier: MPL-2.0
package ranger
import (
"net"
"net/http"
"net/url"
"time"
)
var (
DefaultHttpTimeout = 30 * time.Second
DefaultIdleConnTimeout = 30 * time.Second
DefaultTLSHandshakeTimeout = 10 * time.Second
)
// DefaultHttpClient will set up a basic client
// with default timeouts/proxies/etc.
func DefaultHttpClient() *http.Client {
return NewHttpClient()
}
type HttpClientOption func(c *http.Client)
func WithProxy(proxy *url.URL) HttpClientOption {
return func(c *http.Client) {
if proxy == nil {
return
}
switch t := c.Transport.(type) {
case *http.Transport:
t.Proxy = http.ProxyURL(proxy)
}
}
}
func NewHttpClient(opts ...HttpClientOption) *http.Client {
tr := &http.Transport{
Proxy: http.ProxyFromEnvironment,
DialContext: (&net.Dialer{
Timeout: DefaultHttpTimeout,
KeepAlive: 30 * time.Second,
}).DialContext,
MaxIdleConns: 100,
IdleConnTimeout: DefaultIdleConnTimeout,
TLSHandshakeTimeout: DefaultTLSHandshakeTimeout,
ExpectContinueTimeout: 1 * time.Second,
}
c := &http.Client{
Transport: tr,
Timeout: DefaultHttpTimeout,
}
for i := range opts {
opts[i](c)
}
return c
}