forked from jsteenb2/mess
-
Notifications
You must be signed in to change notification settings - Fork 0
/
grpc.go
81 lines (66 loc) · 2.14 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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
package client
import (
"crypto/tls"
"crypto/x509"
"os"
"strconv"
"time"
"github.com/ThreeDotsLabs/wild-workouts-go-ddd-example/internal/common/genproto/trainer"
"github.com/ThreeDotsLabs/wild-workouts-go-ddd-example/internal/common/genproto/users"
"github.com/pkg/errors"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials"
)
func NewTrainerClient() (client trainer.TrainerServiceClient, close func() error, err error) {
grpcAddr := os.Getenv("TRAINER_GRPC_ADDR")
if grpcAddr == "" {
return nil, func() error { return nil }, errors.New("empty env TRAINER_GRPC_ADDR")
}
opts, err := grpcDialOpts(grpcAddr)
if err != nil {
return nil, func() error { return nil }, err
}
conn, err := grpc.Dial(grpcAddr, opts...)
if err != nil {
return nil, func() error { return nil }, err
}
return trainer.NewTrainerServiceClient(conn), conn.Close, nil
}
func WaitForTrainerService(timeout time.Duration) bool {
return waitForPort(os.Getenv("TRAINER_GRPC_ADDR"), timeout)
}
func NewUsersClient() (client users.UsersServiceClient, close func() error, err error) {
grpcAddr := os.Getenv("USERS_GRPC_ADDR")
if grpcAddr == "" {
return nil, func() error { return nil }, errors.New("empty env USERS_GRPC_ADDR")
}
opts, err := grpcDialOpts(grpcAddr)
if err != nil {
return nil, func() error { return nil }, err
}
conn, err := grpc.Dial(grpcAddr, opts...)
if err != nil {
return nil, func() error { return nil }, err
}
return users.NewUsersServiceClient(conn), conn.Close, nil
}
func WaitForUsersService(timeout time.Duration) bool {
return waitForPort(os.Getenv("USERS_GRPC_ADDR"), timeout)
}
func grpcDialOpts(grpcAddr string) ([]grpc.DialOption, error) {
if noTLS, _ := strconv.ParseBool(os.Getenv("GRPC_NO_TLS")); noTLS {
return []grpc.DialOption{grpc.WithInsecure()}, nil
}
systemRoots, err := x509.SystemCertPool()
if err != nil {
return nil, errors.Wrap(err, "cannot load root CA cert")
}
creds := credentials.NewTLS(&tls.Config{
RootCAs: systemRoots,
MinVersion: tls.VersionTLS12,
})
return []grpc.DialOption{
grpc.WithTransportCredentials(creds),
grpc.WithPerRPCCredentials(newMetadataServerToken(grpcAddr)),
}, nil
}