-
Notifications
You must be signed in to change notification settings - Fork 0
/
conn.go
93 lines (77 loc) · 2.16 KB
/
conn.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
82
83
84
85
86
87
88
89
90
91
92
93
package mx
import (
"context"
"errors"
"google.golang.org/grpc"
)
// SignalConn is a wrapper of grpc.ClientConnInterface, used to capture any type of error when calling Invoke or NewStream method.
// The error will be sent to the errCh channel, which can be obtained by calling the Err method.
type SignalConn struct {
conn grpc.ClientConnInterface
errCh chan error
}
func NewSignalConn(conn grpc.ClientConnInterface) *SignalConn {
return &SignalConn{
conn: conn,
errCh: make(chan error, 1),
}
}
// SignalConn implement grpc.ClientConnInterface
func (s *SignalConn) Invoke(ctx context.Context, method string, args interface{}, reply interface{}, opts ...grpc.CallOption) (err error) {
defer func() {
// recover any type error
if r := recover(); r != nil {
switch _err := r.(type) {
case error:
s.errCh <- _err
err = _err
case string:
s.errCh <- errors.New(_err)
err = errors.New(_err)
default:
s.errCh <- errors.New("unknown error")
err = errors.New("unknown error")
}
}
}()
err = s.conn.Invoke(ctx, method, args, reply, opts...)
if err != nil {
s.errCh <- err
}
return
}
func (s *SignalConn) NewStream(ctx context.Context, desc *grpc.StreamDesc, method string, opts ...grpc.CallOption) (stream grpc.ClientStream, err error) {
defer func() {
// recover any type error
if r := recover(); r != nil {
switch _err := r.(type) {
case error:
s.errCh <- _err
err = _err
case string:
s.errCh <- errors.New(_err)
err = errors.New(_err)
default:
s.errCh <- errors.New("unknown error")
err = errors.New("unknown error")
}
}
}()
stream, err = s.conn.NewStream(ctx, desc, method, opts...)
if err != nil {
s.errCh <- err
}
return
}
func (s *SignalConn) Err() <-chan error {
return s.errCh
}
func (gw *Gateway) DialContext(ctx context.Context, target string, opts ...grpc.DialOption) (*grpc.ClientConn, error) {
opts = append(opts, grpc.WithChainUnaryInterceptor(gw.clientUnaryInterceptors...))
opts = append(opts, grpc.WithChainStreamInterceptor(gw.clientStreamInterceptors...))
conn, err := grpc.DialContext(ctx, target, opts...)
if err != nil {
return nil, err
}
return conn, nil
}