Documentation
¶
Overview ¶
Package validation 提供参数校验功能,用于 enhance 框架。
Package validation 提供参数校验功能,用于 enhance 框架。
该模块提供字段级校验、跨字段校验、校验规则注册等功能,支持 HTTP 中间件集成。 参考 Jakarta Bean Validation (JSR 380) 的设计理念。
架构设计 ¶
- Validator: 校验器接口,定义校验操作
- ValidationRule: 校验规则接口,定义单个校验逻辑
- ValidationContext: 校验上下文,包含被校验对象和错误信息
- ValidationBuilder: 校验构建器,支持链式配置
- ValidationMiddleware: HTTP 校验中间件
- CustomValidator: 自定义验证器接口
- ValidatorRegistry: 验证器注册表,支持并发安全地注册和获取自定义验证器
- MiddlewareValidator: 中间件验证器接口
核心功能 ¶
- 字段级校验: 支持 @Required, @Min, @Max, @Email 等常用校验
- 跨字段校验: 支持比较两个字段的值(如密码确认)
- 规则注册: 支持自定义校验规则
- 错误收集: 收集所有校验错误并返回
- HTTP 集成: 提供 HTTP 中间件自动校验请求参数
使用方式 ¶
定义校验规则:
type User struct {
Name string `validate:"required,min=2,max=50"`
Email string `validate:"required,email"`
Age int `validate:"required,min=18,max=100"`
}
校验对象:
validator := validation.NewValidator()
errs := validator.Validate(user)
if len(errs) > 0 {
// 处理校验错误
}
使用校验构建器:
builder := validation.NewBuilder()
builder.Rule("name").Required().Min(2).Max(50)
builder.Rule("email").Required().Email()
validator := builder.Build()
内置校验规则 ¶
- Required: 必填
- NotBlank: 非空字符串
- Min/Max: 最小/最大值
- Size: 字符串长度或集合大小
- Email: 邮箱格式
- URL: URL 格式
- Regex: 正则表达式匹配
- In: 值在指定列表中
- NotIn: 值不在指定列表中
Package validation 提供参数校验功能,用于 enhance 框架。
Package validation 提供参数校验功能,用于 enhance 框架。
Package validation 提供参数校验功能,用于 enhance 框架。
Index ¶
- func BindAndValidate(req *http.Request, obj any) error
- func DefaultErrorHandler(c any, err error)
- func Validate(value any, rules string) error
- func ValidateStruct(obj any) error
- type Binder
- type CustomValidator
- type DefaultBinder
- type ErrorResponse
- type FormBinder
- type GroupRule
- type GroupedTagValidator
- func (v *GroupedTagValidator) GetGroup(name string) (bool, bool)
- func (v *GroupedTagValidator) RegisterGroup(name string)
- func (v *GroupedTagValidator) SetDefaultGroups(groups ...string)
- func (v *GroupedTagValidator) Validate(obj any) error
- func (v *GroupedTagValidator) ValidateWithGroups(obj any, groups ...string) error
- type JSONBinder
- type MiddlewareConfig
- type MiddlewareValidator
- type QueryBinder
- type RegexCache
- type RequestValidator
- type ResponseWriter
- type RuleBuilder
- func (b *RuleBuilder) Build() string
- func (b *RuleBuilder) BuildWithMessages() (string, map[string]string)
- func (b *RuleBuilder) CustomMessage(message string) *RuleBuilder
- func (b *RuleBuilder) Email() *RuleBuilder
- func (b *RuleBuilder) Gt(n int) *RuleBuilder
- func (b *RuleBuilder) Gte(n int) *RuleBuilder
- func (b *RuleBuilder) IP() *RuleBuilder
- func (b *RuleBuilder) Len(n int) *RuleBuilder
- func (b *RuleBuilder) Lt(n int) *RuleBuilder
- func (b *RuleBuilder) Lte(n int) *RuleBuilder
- func (b *RuleBuilder) Max(n int) *RuleBuilder
- func (b *RuleBuilder) Min(n int) *RuleBuilder
- func (b *RuleBuilder) OneOf(options ...string) *RuleBuilder
- func (b *RuleBuilder) Regexp(pattern string) *RuleBuilder
- func (b *RuleBuilder) Required() *RuleBuilder
- func (b *RuleBuilder) URL() *RuleBuilder
- type RuleValidationError
- type RuleValidationResult
- type TagValidator
- type ValidateMiddleware
- type ValidationConfig
- type ValidationError
- type ValidationErrors
- type ValidationRule
- type Validator
- type ValidatorChain
- type ValidatorRegistry
- func (r *ValidatorRegistry) Get(name string) (CustomValidator, bool)
- func (r *ValidatorRegistry) GetFunc(name string) (func(reflect.Value, string) (bool, string), bool)
- func (r *ValidatorRegistry) Register(name string, validator CustomValidator)
- func (r *ValidatorRegistry) RegisterFunc(name string, validator func(reflect.Value, string) (bool, string))
- func (r *ValidatorRegistry) Unregister(name string)
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func BindAndValidate ¶
BindAndValidate 用于绑定和验证的便捷函数,自动创建绑定器并执行绑定和验证
func DefaultErrorHandler ¶
DefaultErrorHandler 默认错误处理器。
支持多种上下文类型的错误处理:
- http.ResponseWriter: 设置 400 状态码并写入 JSON 错误响应
- ResponseWriter (自定义接口): 统一错误响应
- 其他类型: 仅记录错误信息,不做响应处理
Types ¶
type CustomValidator ¶
type CustomValidator interface {
// Validate 验证字段值。
Validate(field reflect.Value, param string) (bool, string)
}
CustomValidator 自定义验证器接口。
type DefaultBinder ¶
type DefaultBinder struct {
Validator Validator // 验证器实例
}
DefaultBinder 默认绑定器,支持从JSON、表单和查询参数绑定数据
func NewDefaultBinder ¶
func NewDefaultBinder(validator Validator) *DefaultBinder
NewDefaultBinder 创建默认绑定器实例
type ErrorResponse ¶
ErrorResponse 错误响应结构。
用于 HTTP 中间件中的错误响应格式。
func (*ErrorResponse) ToJSON ¶
func (e *ErrorResponse) ToJSON() ([]byte, error)
ToJSON 将错误响应序列化为 JSON 字节。
type GroupedTagValidator ¶
type GroupedTagValidator struct {
// contains filtered or unexported fields
}
GroupedTagValidator 支持验证组的标签验证器。
func NewGroupedValidator ¶
func NewGroupedValidator(registry *ValidatorRegistry) *GroupedTagValidator
NewGroupedValidator 创建新的分组验证器。
func (*GroupedTagValidator) GetGroup ¶
func (v *GroupedTagValidator) GetGroup(name string) (bool, bool)
GetGroup 获取组是否存在。
func (*GroupedTagValidator) RegisterGroup ¶ added in v0.0.3
func (v *GroupedTagValidator) RegisterGroup(name string)
RegisterGroup 注册一个验证组。
func (*GroupedTagValidator) SetDefaultGroups ¶
func (v *GroupedTagValidator) SetDefaultGroups(groups ...string)
SetDefaultGroups 设置默认验证组。
func (*GroupedTagValidator) Validate ¶
func (v *GroupedTagValidator) Validate(obj any) error
Validate 使用默认组验证对象。
func (*GroupedTagValidator) ValidateWithGroups ¶
func (v *GroupedTagValidator) ValidateWithGroups(obj any, groups ...string) error
ValidateWithGroups 使用指定组验证对象。
type MiddlewareConfig ¶
type MiddlewareConfig struct {
Validator Validator
Groups []string
ErrorHandler func(c any, err error)
SkipPaths []string
}
MiddlewareConfig 中间件配置。
type MiddlewareValidator ¶
type MiddlewareValidator interface {
// ValidateRequest 验证请求对象。
ValidateRequest(c any, obj any) error
// HandleValidationError 处理验证错误。
HandleValidationError(c any, err error)
}
MiddlewareValidator 中间件验证器接口。
type QueryBinder ¶
type QueryBinder struct {
Validator Validator
}
QueryBinder 专门用于查询参数绑定的绑定器
func NewQueryBinder ¶
func NewQueryBinder(validator Validator) *QueryBinder
NewQueryBinder 创建查询参数绑定器实例
type RegexCache ¶
type RegexCache struct {
// contains filtered or unexported fields
}
RegexCache 正则表达式缓存。
func (*RegexCache) Get ¶
func (c *RegexCache) Get(pattern string) (*regexp.Regexp, error)
Get 获取或编译正则表达式。
type RequestValidator ¶
type RequestValidator struct {
// contains filtered or unexported fields
}
RequestValidator HTTP 请求验证器。
func NewRequestValidator ¶
func NewRequestValidator(config ValidationConfig) (*RequestValidator, error)
NewRequestValidator 创建请求验证器
func (*RequestValidator) GetConfig ¶
func (v *RequestValidator) GetConfig() ValidationConfig
GetConfig 获取验证配置。
func (*RequestValidator) Validate ¶
func (v *RequestValidator) Validate(req *http.Request) *RuleValidationResult
Validate 验证请求。
type ResponseWriter ¶ added in v0.0.4
type ResponseWriter interface {
// SetStatusCode 设置 HTTP 状态码。
SetStatusCode(code int)
// SetHeader 设置响应头。
SetHeader(key, value string)
// Write 写入响应体。
Write(data []byte) error
}
ResponseWriter 响应写入器接口。
抽象层,适配不同 HTTP 框架的响应写入。
type RuleBuilder ¶
type RuleBuilder struct {
// contains filtered or unexported fields
}
RuleBuilder 验证规则构建器。
支持链式配置校验规则。
func (*RuleBuilder) BuildWithMessages ¶
func (b *RuleBuilder) BuildWithMessages() (string, map[string]string)
BuildWithMessages 构建验证规则并返回消息映射。
func (*RuleBuilder) CustomMessage ¶
func (b *RuleBuilder) CustomMessage(message string) *RuleBuilder
CustomMessage 设置自定义错误消息。
func (*RuleBuilder) OneOf ¶
func (b *RuleBuilder) OneOf(options ...string) *RuleBuilder
OneOf 添加枚举值验证。
func (*RuleBuilder) Regexp ¶
func (b *RuleBuilder) Regexp(pattern string) *RuleBuilder
Regexp 添加正则表达式验证。
type RuleValidationError ¶
type RuleValidationError struct {
// Field 字段名称
Field string `json:"field"`
// Message 错误消息
Message string `json:"message"`
// Type 错误类型
Type string `json:"type"`
}
RuleValidationError 验证错误。
type RuleValidationResult ¶
type RuleValidationResult struct {
// Valid 是否通过验证
Valid bool `json:"valid"`
// Errors 错误列表
Errors []RuleValidationError `json:"errors,omitempty"`
}
RuleValidationResult 验证结果。
func ValidateHeaders ¶
func ValidateHeaders(req *http.Request, rules []ValidationRule) *RuleValidationResult
ValidateHeaders 快速验证请求头。
func ValidateJSONBody ¶
func ValidateJSONBody(body []byte, rules []ValidationRule) *RuleValidationResult
ValidateJSONBody 验证 JSON body。
func ValidateQuery ¶
func ValidateQuery(req *http.Request, rules []ValidationRule) *RuleValidationResult
ValidateQuery 快速验证查询参数。
type TagValidator ¶
type TagValidator struct {
// contains filtered or unexported fields
}
TagValidator 基于标签的验证器。
支持多种验证规则,通过结构体标签定义校验规则。
func NewTagValidatorWithRegistry ¶
func NewTagValidatorWithRegistry(registry *ValidatorRegistry) *TagValidator
NewTagValidatorWithRegistry 创建带有注册表的标签验证器实例
func (*TagValidator) Validate ¶
func (v *TagValidator) Validate(obj any) error
Validate 验证对象,对结构体的字段进行验证
type ValidateMiddleware ¶
type ValidateMiddleware func(c any, obj any, config *MiddlewareConfig) error
ValidateMiddleware 通用验证中间件函数类型。
func NewValidateMiddleware ¶
func NewValidateMiddleware(config *MiddlewareConfig) ValidateMiddleware
NewValidateMiddleware 创建新的验证中间件。
type ValidationConfig ¶
type ValidationConfig struct {
// Rules 验证规则
Rules []ValidationRule `json:"rules"`
// Source 验证来源:query, header, body
Source string `json:"source"`
// FailFast 快速失败(遇到第一个错误就停止)
FailFast bool `json:"fail_fast"`
}
ValidationConfig 验证配置。
type ValidationError ¶
type ValidationError struct {
Field string `json:"field"` // 字段名称
Message string `json:"message"` // 错误消息
Value any `json:"value,omitempty"` // 实际值
}
ValidationError 验证错误结构。
包含字段名称、错误消息和实际值。
func (ValidationError) Error ¶
func (e ValidationError) Error() string
type ValidationErrors ¶
type ValidationErrors []ValidationError
ValidationErrors 验证错误集合。
实现了错误接口,包含多个验证错误。
func (ValidationErrors) Error ¶
func (e ValidationErrors) Error() string
type ValidationRule ¶
type ValidationRule struct {
// Field 字段名称
Field string `json:"field"`
// Type 验证类型:required, string, number, email, regex, enum, min, max, length
Type string `json:"type"`
// Value 验证值(用于 enum, regex 等)
Value string `json:"value,omitempty"`
// Min 最小值
Min *float64 `json:"min,omitempty"`
// Max 最大值
Max *float64 `json:"max,omitempty"`
// MinLength 最小长度
MinLength *int `json:"min_length,omitempty"`
// MaxLength 最大长度
MaxLength *int `json:"max_length,omitempty"`
// Pattern 正则表达式
Pattern string `json:"pattern,omitempty"`
// Message 自定义错误消息
Message string `json:"message,omitempty"`
// In 枚举值
In []string `json:"in,omitempty"`
}
ValidationRule 验证规则。
func (ValidationRule) MessageOrDefault ¶
func (r ValidationRule) MessageOrDefault(format string, args ...any) string
MessageOrDefault 获取自定义消息或默认消息。
type ValidatorChain ¶
type ValidatorChain struct {
// contains filtered or unexported fields
}
ValidatorChain 验证器链,支持多个对象连续验证。
func (*ValidatorChain) AddStruct ¶
func (c *ValidatorChain) AddStruct(obj any) *ValidatorChain
AddStruct 添加结构体验证器。
func (*ValidatorChain) AddValue ¶
func (c *ValidatorChain) AddValue(value any, rules string) *ValidatorChain
AddValue 添加值验证器。
func (*ValidatorChain) StopOnFirstError ¶
func (c *ValidatorChain) StopOnFirstError() *ValidatorChain
StopOnFirstError 设置遇到第一个错误时停止。
type ValidatorRegistry ¶
type ValidatorRegistry struct {
// contains filtered or unexported fields
}
ValidatorRegistry 验证器注册表。
支持并发安全地注册和获取自定义验证器。 使用 sync.Map 优化读多写少场景的并发性能。
func NewValidatorRegistry ¶
func NewValidatorRegistry() *ValidatorRegistry
NewValidatorRegistry 创建新的验证器注册表。
func (*ValidatorRegistry) Get ¶
func (r *ValidatorRegistry) Get(name string) (CustomValidator, bool)
Get 获取结构体验证器。
func (*ValidatorRegistry) Register ¶
func (r *ValidatorRegistry) Register(name string, validator CustomValidator)
Register 注册结构体验证器。
func (*ValidatorRegistry) RegisterFunc ¶
func (r *ValidatorRegistry) RegisterFunc(name string, validator func(reflect.Value, string) (bool, string))
RegisterFunc 注册函数式验证器。
func (*ValidatorRegistry) Unregister ¶
func (r *ValidatorRegistry) Unregister(name string)
Unregister 注销验证器。