-
Notifications
You must be signed in to change notification settings - Fork 14
/
grpc.go
58 lines (49 loc) · 1.59 KB
/
grpc.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
package config
import (
"context"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials"
)
func ExtractGrpcServerOptions(ctx context.Context, cfg *GRPCServerConfig) ([]grpc.ServerOption, error) {
if cfg == nil || cfg.TLS == nil {
return []grpc.ServerOption{}, nil
}
tlsConfig, err := MakeTLSConfig(ctx, cfg.TLS)
if err != nil {
return nil, err
}
creds := credentials.NewTLS(tlsConfig)
return []grpc.ServerOption{grpc.Creds(creds)}, nil
}
// CommonGRPCDownstreamData collects all the client gRPC configuration.
type CommonGRPCDownstreamData struct {
ServiceAddress string `yaml:"serviceAddress" mapstructure:"serviceAddress"`
TLS *TLSConfig `yaml:"tls" mapstructure:"tls"`
WithBlock bool `yaml:"withBlock" mapstructure:"withBlock"`
}
func NewDefaultCommonGRPCDownstreamData() *CommonGRPCDownstreamData {
return &CommonGRPCDownstreamData{}
}
// DefaultGRPDialOptions creates []grpc.DialOption from the given config.
// If cfg is nil then NewDefaultCommonGRPCDownstreamData will be used to define
// the dial options.
func DefaultGrpcDialOptions(ctx context.Context, cfg *CommonGRPCDownstreamData) ([]grpc.DialOption, error) {
if cfg == nil {
cfg = NewDefaultCommonGRPCDownstreamData()
}
var opts []grpc.DialOption
if cfg.TLS != nil {
tlsConfig, err := MakeTLSConfig(ctx, cfg.TLS)
if err != nil {
return nil, err
}
creds := credentials.NewTLS(tlsConfig)
opts = append(opts, grpc.WithTransportCredentials(creds))
} else {
opts = append(opts, grpc.WithInsecure())
}
if cfg.WithBlock {
opts = append(opts, grpc.WithBlock())
}
return opts, nil
}