38 lines
839 B
Go
38 lines
839 B
Go
package validate
|
|
|
|
import (
|
|
"context"
|
|
|
|
"buf.build/go/protovalidate"
|
|
"google.golang.org/grpc"
|
|
"google.golang.org/grpc/codes"
|
|
"google.golang.org/grpc/status"
|
|
"google.golang.org/protobuf/proto"
|
|
)
|
|
|
|
// UnaryServerInterceptor runs protovalidate on every unary request before logic.
|
|
func UnaryServerInterceptor(v protovalidate.Validator) grpc.UnaryServerInterceptor {
|
|
return func(
|
|
ctx context.Context,
|
|
req any,
|
|
_ *grpc.UnaryServerInfo,
|
|
handler grpc.UnaryHandler,
|
|
) (any, error) {
|
|
if msg, ok := req.(proto.Message); ok {
|
|
if err := v.Validate(msg); err != nil {
|
|
return nil, status.Error(codes.InvalidArgument, err.Error())
|
|
}
|
|
}
|
|
return handler(ctx, req)
|
|
}
|
|
}
|
|
|
|
// MustNew creates a Validator or panics.
|
|
func MustNew() protovalidate.Validator {
|
|
v, err := protovalidate.New()
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
return v
|
|
}
|