-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclients.go
81 lines (71 loc) · 1.8 KB
/
clients.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
package http
import (
"crypto/tls"
"crypto/x509"
"net/http"
"os"
"time"
)
// DefaultClient returns an HTTP client with a 5-second timeout.
func DefaultClient() *http.Client {
return &http.Client{
Timeout: 5 * time.Second,
}
}
// NewTLSClientInsecure returns an HTTP client configured for simple TLS, but
// skipping server certificate verification.
func NewTLSClientInsecure(skipVerify bool) (*http.Client, error) {
return &http.Client{
Transport: &http.Transport{
TLSClientConfig: &tls.Config{
InsecureSkipVerify: true,
},
},
Timeout: 5 * time.Second,
}, nil
}
// NewTLSClient returns an HTTP client configured for simple TLS, using the
// provided CA certificate.
func NewTLSClient(caCertPath string) (*http.Client, error) {
config := &tls.Config{}
asn1Data, err := os.ReadFile(caCertPath)
if err != nil {
return nil, err
}
config.RootCAs = x509.NewCertPool()
ok := config.RootCAs.AppendCertsFromPEM(asn1Data)
if !ok {
return nil, err
}
return &http.Client{
Transport: &http.Transport{
TLSClientConfig: config,
},
Timeout: 5 * time.Second,
}, nil
}
// NewMutualTLSClient returns an HTTP client configured for mutual TLS.
// It accepts paths for the client cert, client key, and trusted CA.
func NewMutualTLSClient(clientCertPath, clientKeyPath, caCertPath string) (*http.Client, error) {
config := &tls.Config{}
asn1Data, err := os.ReadFile(caCertPath)
if err != nil {
return nil, err
}
config.RootCAs = x509.NewCertPool()
ok := config.RootCAs.AppendCertsFromPEM(asn1Data)
if !ok {
return nil, err
}
cert, err := tls.LoadX509KeyPair(clientCertPath, clientKeyPath)
if err != nil {
return nil, err
}
config.Certificates = []tls.Certificate{cert}
return &http.Client{
Transport: &http.Transport{
TLSClientConfig: config,
},
Timeout: 5 * time.Second,
}, nil
}