-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathdial.go
60 lines (45 loc) · 1.71 KB
/
dial.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
package grpctools
import (
"context"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
)
// Dial creates a client connection.
func Dial(target string, opts *DialOptions, extra ...grpc.DialOption) (*grpc.ClientConn, error) {
return DialContext(context.Background(), target, opts, extra...)
}
// DialContext creates a client connection with specified context.
func DialContext(ctx context.Context, target string, opts *DialOptions, extra ...grpc.DialOption) (*grpc.ClientConn, error) {
if opts == nil {
opts = new(DialOptions)
}
full := append(opts.grpcDialOpts(), extra...)
return grpc.DialContext(ctx, target, full...)
}
// --------------------------------------------------------------------
// DialOptions represent dial options.
type DialOptions struct {
// Enables transport security.
SkipInsecure bool
// Makes Dial non-blocking (Dial won't wait for connection to be up before returning).
SkipBlock bool
// Unary client interceptors.
UnaryInterceptors []grpc.UnaryClientInterceptor
// Stream client interceptors.
StreamInterceptors []grpc.StreamClientInterceptor
}
func (o *DialOptions) grpcDialOpts() (opts []grpc.DialOption) {
if !o.SkipInsecure {
opts = append(opts, grpc.WithTransportCredentials(insecure.NewCredentials()))
}
if !o.SkipBlock {
opts = append(opts, grpc.WithBlock())
}
if chain := append([]grpc.UnaryClientInterceptor{}, o.UnaryInterceptors...); len(chain) != 0 {
opts = append(opts, grpc.WithUnaryInterceptor(unaryClientInterceptorChain(chain...)))
}
if chain := append([]grpc.StreamClientInterceptor{}, o.StreamInterceptors...); len(chain) != 0 {
opts = append(opts, grpc.WithStreamInterceptor(streamClientInterceptorChain(chain...)))
}
return opts
}