|
1 | 1 | package httpclient |
2 | 2 |
|
3 | 3 | import ( |
| 4 | + "context" |
4 | 5 | "crypto/tls" |
5 | 6 | "crypto/x509" |
6 | 7 | "errors" |
7 | 8 | "fmt" |
8 | 9 | "net" |
9 | 10 | "net/http" |
| 11 | + "time" |
10 | 12 |
|
11 | 13 | "github.com/grafana/grafana-plugin-sdk-go/backend/proxy" |
12 | 14 | ) |
@@ -50,7 +52,7 @@ func New(opts ...Options) (*http.Client, error) { |
50 | 52 | // Note: If more than one Options is provided a panic is raised. |
51 | 53 | func GetTransport(opts ...Options) (http.RoundTripper, error) { |
52 | 54 | if opts == nil { |
53 | | - return GetDefaultTransport() |
| 55 | + return NewHTTPTransport(), nil |
54 | 56 | } |
55 | 57 |
|
56 | 58 | clientOpts := createOptions(opts...) |
@@ -96,14 +98,30 @@ func GetTransport(opts ...Options) (http.RoundTripper, error) { |
96 | 98 | return roundTripperFromMiddlewares(clientOpts, clientOpts.Middlewares, transport) |
97 | 99 | } |
98 | 100 |
|
99 | | -// GetDefaultTransport returns a clone of http.DefaultTransport, if it's of the |
100 | | -// correct type, or an error otherwise. There are a number of places where plugin |
101 | | -// code uses http.DefaultTransport; this supports doing so in a safer way. |
102 | | -func GetDefaultTransport() (http.RoundTripper, error) { |
103 | | - if transport, ok := http.DefaultTransport.(*http.Transport); ok { |
104 | | - return transport.Clone(), nil |
| 101 | +// NewHTTPTransport returns a new HTTP Transport, based off the definition in |
| 102 | +// the stdlib http.DefaultTransport. It's not a clone, because that would return |
| 103 | +// any mutations of http.DefaultTransport from other code at the time of the call. |
| 104 | +// Any plugin that needs a default http transport should use this function. |
| 105 | +func NewHTTPTransport() http.RoundTripper { |
| 106 | + return &http.Transport{ |
| 107 | + Proxy: http.ProxyFromEnvironment, |
| 108 | + DialContext: func(dialer *net.Dialer) func(context.Context, string, string) (net.Conn, error) { |
| 109 | + return dialer.DialContext |
| 110 | + }(&net.Dialer{ |
| 111 | + Timeout: 30 * time.Second, |
| 112 | + KeepAlive: 30 * time.Second, |
| 113 | + }), |
| 114 | + ForceAttemptHTTP2: true, |
| 115 | + MaxIdleConns: 100, |
| 116 | + IdleConnTimeout: 90 * time.Second, |
| 117 | + TLSHandshakeTimeout: 10 * time.Second, |
| 118 | + ExpectContinueTimeout: 1 * time.Second, |
105 | 119 | } |
106 | | - return nil, fmt.Errorf("http.DefaultTransport is not *http.Transport but %T", http.DefaultTransport) |
| 120 | +} |
| 121 | + |
| 122 | +// Deprecated - use NewHTTPTransport. Keeping for backwards compatibility. |
| 123 | +func GetDefaultTransport() (http.RoundTripper, error) { |
| 124 | + return NewHTTPTransport(), nil |
107 | 125 | } |
108 | 126 |
|
109 | 127 | // GetTLSConfig creates a new tls.Config given provided options. |
|
0 commit comments