-
Notifications
You must be signed in to change notification settings - Fork 0
/
clientconn.go
71 lines (61 loc) · 1.74 KB
/
clientconn.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
package grpcmtls
import (
context "context"
"crypto/tls"
"crypto/x509"
"fmt"
"math"
"os"
"time"
grpcmiddleware "github.com/grpc-ecosystem/go-grpc-middleware"
grpcretry "github.com/grpc-ecosystem/go-grpc-middleware/retry"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials"
)
func NewClientConnGrpc(ctx context.Context, addr string, certs ClientCertFiles) (*grpc.ClientConn, error) {
cert, err := tls.LoadX509KeyPair(certs.ClientCertPemFilePath, certs.ClientKeyPemFilePath)
if err != nil {
return nil, fmt.Errorf("failed to load client cert: %w", err)
}
ca := x509.NewCertPool()
caBytes, err := os.ReadFile(certs.CAFilePath)
if err != nil {
return nil, fmt.Errorf("failed to read ca cert %q: %w", certs.CAFilePath, err)
}
if ok := ca.AppendCertsFromPEM(caBytes); !ok {
return nil, fmt.Errorf("failed to parse %q", certs.CAFilePath)
}
tlsConfig := &tls.Config{
ServerName: "localhost",
Certificates: []tls.Certificate{cert},
RootCAs: ca,
MinVersion: tls.VersionTLS13,
MaxVersion: tls.VersionTLS13,
}
opts := []grpcretry.CallOption{
grpcretry.WithBackoff(grpcretry.BackoffExponential(100 * time.Millisecond)),
grpcretry.WithMax(5),
}
maxMessageSize := math.MaxInt32 // 2Gb
conn, err := grpc.DialContext(ctx, addr,
grpc.WithTransportCredentials(credentials.NewTLS(tlsConfig)),
grpc.WithDefaultCallOptions(
grpc.MaxCallRecvMsgSize(maxMessageSize),
grpc.MaxCallSendMsgSize(maxMessageSize),
),
grpc.WithStreamInterceptor(
grpcmiddleware.ChainStreamClient(
grpcretry.StreamClientInterceptor(opts...),
),
),
grpc.WithUnaryInterceptor(
grpcmiddleware.ChainUnaryClient(
grpcretry.UnaryClientInterceptor(opts...),
),
),
)
if err != nil {
return nil, err
}
return conn, nil
}