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
85
86
87
88
89
90
91
92
93
94
|
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package util
import (
"context"
"crypto/tls"
"fmt"
"net"
"net/http"
"time"
"github.com/vespa-engine/vespa/client/go/internal/build"
"golang.org/x/net/http2"
)
type HTTPClient interface {
Do(request *http.Request, timeout time.Duration) (response *http.Response, error error)
Clone() HTTPClient
}
type defaultHTTPClient struct {
client *http.Client
}
func (c *defaultHTTPClient) Do(request *http.Request, timeout time.Duration) (response *http.Response, error error) {
if c.client.Timeout != timeout { // Set wanted timeout
c.client.Timeout = timeout
}
if request.Header == nil {
request.Header = make(http.Header)
}
request.Header.Set("User-Agent", fmt.Sprintf("Vespa CLI/%s", build.Version))
return c.client.Do(request)
}
func (c *defaultHTTPClient) Clone() HTTPClient { return CreateClient(c.client.Timeout) }
func SetCertificates(client HTTPClient, certificates []tls.Certificate) {
c, ok := client.(*defaultHTTPClient)
if !ok {
return
}
var tlsConfig *tls.Config = nil
if certificates != nil {
tlsConfig = &tls.Config{
Certificates: certificates,
MinVersion: tls.VersionTLS12,
}
}
if tr, ok := c.client.Transport.(*http.Transport); ok {
tr.TLSClientConfig = tlsConfig
} else if tr, ok := c.client.Transport.(*http2.Transport); ok {
tr.TLSClientConfig = tlsConfig
} else {
panic(fmt.Sprintf("unknown transport type: %T", c.client.Transport))
}
}
func ForceHTTP2(client HTTPClient, certificates []tls.Certificate) {
c, ok := client.(*defaultHTTPClient)
if !ok {
return
}
var tlsConfig *tls.Config = nil
var dialFunc func(ctx context.Context, network, addr string, cfg *tls.Config) (net.Conn, error)
if certificates != nil {
tlsConfig = &tls.Config{
Certificates: certificates,
MinVersion: tls.VersionTLS12,
}
} else {
// No certificate, so force H2C (HTTP/2 over clear-text) by using a non-TLS Dialer
dialer := net.Dialer{}
dialFunc = func(ctx context.Context, network, addr string, cfg *tls.Config) (net.Conn, error) {
return dialer.DialContext(ctx, network, addr)
}
}
// Use HTTP/2 transport explicitly. Connection reuse does not work properly when using regular http.Transport, even
// though it upgrades to HTTP/2 automatically
// https://github.com/golang/go/issues/16582
// https://github.com/golang/go/issues/22091
c.client.Transport = &http2.Transport{
AllowHTTP: true,
TLSClientConfig: tlsConfig,
DialTLSContext: dialFunc,
}
}
func CreateClient(timeout time.Duration) HTTPClient {
return &defaultHTTPClient{client: &http.Client{
Timeout: timeout,
Transport: http.DefaultTransport,
}}
}
|