@@ -11,19 +11,38 @@ import (
11
11
"google.golang.org/grpc/status"
12
12
)
13
13
14
+ // The validate interface starting with protoc-gen-validate v0.6.0.
15
+ // See https://github.com/envoyproxy/protoc-gen-validate/pull/455.
14
16
type validator interface {
17
+ Validate (all bool ) error
18
+ }
19
+
20
+ // The validate interface prior to protoc-gen-validate v0.6.0.
21
+ type validatorLegacy interface {
15
22
Validate () error
16
23
}
17
24
25
+ func validate (req interface {}) error {
26
+ switch v := req .(type ) {
27
+ case validatorLegacy :
28
+ if err := v .Validate (); err != nil {
29
+ return status .Error (codes .InvalidArgument , err .Error ())
30
+ }
31
+ case validator :
32
+ if err := v .Validate (false ); err != nil {
33
+ return status .Error (codes .InvalidArgument , err .Error ())
34
+ }
35
+ }
36
+ return nil
37
+ }
38
+
18
39
// UnaryServerInterceptor returns a new unary server interceptor that validates incoming messages.
19
40
//
20
41
// Invalid messages will be rejected with `InvalidArgument` before reaching any userspace handlers.
21
42
func UnaryServerInterceptor () grpc.UnaryServerInterceptor {
22
43
return func (ctx context.Context , req interface {}, info * grpc.UnaryServerInfo , handler grpc.UnaryHandler ) (interface {}, error ) {
23
- if v , ok := req .(validator ); ok {
24
- if err := v .Validate (); err != nil {
25
- return nil , status .Error (codes .InvalidArgument , err .Error ())
26
- }
44
+ if err := validate (req ); err != nil {
45
+ return nil , err
27
46
}
28
47
return handler (ctx , req )
29
48
}
@@ -34,10 +53,8 @@ func UnaryServerInterceptor() grpc.UnaryServerInterceptor {
34
53
// Invalid messages will be rejected with `InvalidArgument` before sending the request to server.
35
54
func UnaryClientInterceptor () grpc.UnaryClientInterceptor {
36
55
return func (ctx context.Context , method string , req , reply interface {}, cc * grpc.ClientConn , invoker grpc.UnaryInvoker , opts ... grpc.CallOption ) error {
37
- if v , ok := req .(validator ); ok {
38
- if err := v .Validate (); err != nil {
39
- return status .Error (codes .InvalidArgument , err .Error ())
40
- }
56
+ if err := validate (req ); err != nil {
57
+ return err
41
58
}
42
59
return invoker (ctx , method , req , reply , cc , opts ... )
43
60
}
@@ -64,10 +81,10 @@ func (s *recvWrapper) RecvMsg(m interface{}) error {
64
81
if err := s .ServerStream .RecvMsg (m ); err != nil {
65
82
return err
66
83
}
67
- if v , ok := m .(validator ); ok {
68
- if err := v .Validate (); err != nil {
69
- return status .Error (codes .InvalidArgument , err .Error ())
70
- }
84
+
85
+ if err := validate (m ); err != nil {
86
+ return err
71
87
}
88
+
72
89
return nil
73
90
}
0 commit comments