-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathclientunaryinterceptor.go
64 lines (52 loc) · 1.44 KB
/
clientunaryinterceptor.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
// Copyright (c) 2022 Dmitry Tkachenko ([email protected])
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package care
import (
"context"
"google.golang.org/grpc"
"reflect"
)
type unaryClientInterceptor struct {
interceptor *interceptor
}
func (s *unaryClientInterceptor) Unary() grpc.UnaryClientInterceptor {
return func(
ctx context.Context,
method string,
req, reply interface{},
cc *grpc.ClientConn,
invoker grpc.UnaryInvoker,
opts ...grpc.CallOption) error {
realComputation := false
resp, err := s.interceptor.execute(
ctx,
method,
req,
func(c context.Context, r interface{}) (interface{}, error) {
e := invoker(c, method, r, reply, cc, opts...)
realComputation = true
return reply, e
},
)
if !realComputation && resp != nil {
replyVal := reflect.ValueOf(reply).Elem()
respVal := reflect.ValueOf(resp).Elem()
tmp := replyVal.Interface()
replyVal.Set(respVal)
respVal.Set(reflect.ValueOf(tmp))
}
return err
}
}
// NewClientUnaryInterceptor makes a new unary client interceptor.
// There will be panic if options is an empty pointer.
func NewClientUnaryInterceptor(opts *Options) grpc.DialOption {
if opts == nil {
panic("The options must not be provided as a nil-pointer.")
}
interceptor := unaryClientInterceptor{
interceptor: newInterceptor(opts),
}
return grpc.WithUnaryInterceptor(interceptor.Unary())
}