-
Notifications
You must be signed in to change notification settings - Fork 1
/
dial_options_provider.go
69 lines (58 loc) · 1.83 KB
/
dial_options_provider.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
package aserto
import (
"context"
"crypto/tls"
"github.com/pkg/errors"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials"
"google.golang.org/grpc/metadata"
)
type DialOptionsProvider func(*Config) ([]grpc.DialOption, error)
func NewDialOptionsProvider(dialopts ...grpc.DialOption) DialOptionsProvider {
return func(cfg *Config) ([]grpc.DialOption, error) {
if (cfg.ClientCertPath != "") != (cfg.ClientKeyPath != "") {
return nil, errors.New("both client cert and key must be specified, or both must be empty")
}
if cfg.ClientCertPath != "" {
certificate, err := tls.LoadX509KeyPair(cfg.ClientCertPath, cfg.ClientKeyPath)
if err != nil {
return nil, errors.Wrapf(err, "failed to load client GRPC certs")
}
tlsConfig := &tls.Config{
Certificates: []tls.Certificate{certificate},
MinVersion: tls.VersionTLS12,
}
dialopts = append(dialopts, grpc.WithTransportCredentials(credentials.NewTLS(tlsConfig)))
}
var pairs []string
for k, v := range cfg.Headers {
pairs = append(pairs, k, v)
}
if pairs != nil {
//nolint: gocritic
dialopts = append(dialopts, grpc.WithUnaryInterceptor(
func(ctx context.Context,
method string,
req, reply interface{},
cc *grpc.ClientConn,
invoker grpc.UnaryInvoker,
opts ...grpc.CallOption,
) error {
ctx = metadata.AppendToOutgoingContext(ctx, pairs...)
return invoker(ctx, method, req, reply, cc, opts...)
}))
dialopts = append(dialopts, grpc.WithStreamInterceptor(
func(ctx context.Context,
desc *grpc.StreamDesc,
cc *grpc.ClientConn,
method string,
streamer grpc.Streamer,
opts ...grpc.CallOption,
) (grpc.ClientStream, error) {
ctx = metadata.AppendToOutgoingContext(ctx, pairs...)
return streamer(ctx, desc, cc, method, opts...)
}))
}
return dialopts, nil
}
}