| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123 |
- package validator
- import (
- "context"
- "google.golang.org/protobuf/proto"
- )
- // Validator 验证器接口
- type Validator interface {
- // Validate 验证消息
- Validate(ctx context.Context, msg proto.Message) error
- // ValidateWithGroups 使用指定组验证消息
- ValidateWithGroups(ctx context.Context, msg proto.Message, groups ...string) error
- // ValidateField 验证单个字段
- ValidateField(ctx context.Context, fieldPath string, value interface{}, rules interface{}) error
- }
- // validator 默认验证器实现
- type validator struct {
- engine *Engine
- celExecutor *CELExecutor
- }
- // New 创建新的验证器
- func New(opts ...Option) (Validator, error) {
- // 创建 CEL 执行器
- celExecutor, err := NewCELExecutor()
- if err != nil {
- return nil, err
- }
- // 创建验证引擎
- engine := NewEngine(celExecutor)
- v := &validator{
- engine: engine,
- celExecutor: celExecutor,
- }
- // 应用选项
- for _, opt := range opts {
- opt(v)
- }
- return v, nil
- }
- // Validate 验证消息
- func (v *validator) Validate(ctx context.Context, msg proto.Message) error {
- if msg == nil {
- return nil
- }
- // 从上下文创建验证上下文
- vctx := FromContext(ctx)
- // 执行验证
- return v.engine.Validate(vctx, msg)
- }
- // ValidateWithGroups 使用指定组验证消息
- func (v *validator) ValidateWithGroups(ctx context.Context, msg proto.Message, groups ...string) error {
- if msg == nil {
- return nil
- }
- // 创建验证上下文并设置组
- vctx := FromContext(ctx)
- vctx.Groups = groups
- // 执行验证
- return v.engine.Validate(vctx, msg)
- }
- // ValidateField 验证单个字段
- func (v *validator) ValidateField(ctx context.Context, fieldPath string, value interface{}, rules interface{}) error {
- vctx := FromContext(ctx)
- return v.engine.ValidateField(vctx, fieldPath, value, rules)
- }
- // Option 验证器选项
- type Option func(*validator)
- // WithCELFunctions 添加自定义 CEL 函数(暂时保留接口,未来扩展)
- func WithCELFunctions() Option {
- return func(v *validator) {
- // TODO: 实现自定义 CEL 函数注册
- }
- }
- // MustNew 创建验证器,如果失败则 panic
- func MustNew(opts ...Option) Validator {
- v, err := New(opts...)
- if err != nil {
- panic(err)
- }
- return v
- }
- // 全局默认验证器
- var defaultValidator Validator
- // init 初始化默认验证器
- func init() {
- var err error
- defaultValidator, err = New()
- if err != nil {
- panic(err)
- }
- }
- // Validate 使用默认验证器验证消息
- func Validate(ctx context.Context, msg proto.Message) error {
- return defaultValidator.Validate(ctx, msg)
- }
- // ValidateWithGroups 使用默认验证器和指定组验证消息
- func ValidateWithGroups(ctx context.Context, msg proto.Message, groups ...string) error {
- return defaultValidator.ValidateWithGroups(ctx, msg, groups...)
- }
|