forked from grpc-ecosystem/go-grpc-middleware
-
Notifications
You must be signed in to change notification settings - Fork 0
/
validator.go
57 lines (48 loc) · 1.31 KB
/
validator.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
// Copyright (c) The go-grpc-middleware Authors.
// Licensed under the Apache License 2.0.
package validator
import (
"context"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
// The validateAller interface at protoc-gen-validate main branch.
// See https://github.com/envoyproxy/protoc-gen-validate/pull/468.
type validateAller interface {
ValidateAll() error
}
// The validate interface starting with protoc-gen-validate v0.6.0.
// See https://github.com/envoyproxy/protoc-gen-validate/pull/455.
type validator interface {
Validate(all bool) error
}
// The validate interface prior to protoc-gen-validate v0.6.0.
type validatorLegacy interface {
Validate() error
}
func validate(ctx context.Context, reqOrRes interface{}, shouldFailFast bool, onValidationErrCallback OnValidationErrCallback) (err error) {
if shouldFailFast {
switch v := reqOrRes.(type) {
case validatorLegacy:
err = v.Validate()
case validator:
err = v.Validate(false)
}
} else {
switch v := reqOrRes.(type) {
case validateAller:
err = v.ValidateAll()
case validator:
err = v.Validate(true)
case validatorLegacy:
err = v.Validate()
}
}
if err == nil {
return nil
}
if onValidationErrCallback != nil {
onValidationErrCallback(ctx, err)
}
return status.Error(codes.InvalidArgument, err.Error())
}