forked from delimitrou/DeathStarBench
-
Notifications
You must be signed in to change notification settings - Fork 0
/
dialer.go
66 lines (56 loc) · 1.72 KB
/
dialer.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
package dialer
import (
"fmt"
"time"
"github.com/grpc-ecosystem/grpc-opentracing/go/otgrpc"
"github.com/harlow/go-micro-services/tls"
consul "github.com/hashicorp/consul/api"
lb "github.com/olivere/grpc/lb/consul"
opentracing "github.com/opentracing/opentracing-go"
"google.golang.org/grpc"
"google.golang.org/grpc/keepalive"
)
// DialOption allows optional config for dialer
type DialOption func(name string) (grpc.DialOption, error)
// WithTracer traces rpc calls
func WithTracer(tracer opentracing.Tracer) DialOption {
return func(name string) (grpc.DialOption, error) {
return grpc.WithUnaryInterceptor(otgrpc.OpenTracingClientInterceptor(tracer)), nil
}
}
// WithBalancer enables client side load balancing
func WithBalancer(registry *consul.Client) DialOption {
return func(name string) (grpc.DialOption, error) {
r, err := lb.NewResolver(registry, name, "")
if err != nil {
return nil, err
}
return grpc.WithBalancer(grpc.RoundRobin(r)), nil
}
}
// Dial returns a load balanced grpc client conn with tracing interceptor
func Dial(name string, opts ...DialOption) (*grpc.ClientConn, error) {
dialopts := []grpc.DialOption{
grpc.WithKeepaliveParams(keepalive.ClientParameters{
Timeout: 120 * time.Second,
PermitWithoutStream: true,
}),
}
if tlsopt := tls.GetDialOpt(); tlsopt != nil {
dialopts = append(dialopts, tlsopt)
} else {
dialopts = append(dialopts, grpc.WithInsecure())
}
for _, fn := range opts {
opt, err := fn(name)
if err != nil {
return nil, fmt.Errorf("config error: %v", err)
}
dialopts = append(dialopts, opt)
}
conn, err := grpc.Dial(name, dialopts...)
if err != nil {
return nil, fmt.Errorf("failed to dial %s: %v", name, err)
}
return conn, nil
}