Documentation
¶
Overview ¶
Package validator 提供零依赖 struct tag 校验和服务网关常用校验能力
Index ¶
- Constants
- func ClearRegexCache()
- func ContainsChinese(s string) bool
- func DerefValue(value interface{}) (interface{}, bool)
- func EmptyToDefault(str string, defaultStr string) string
- func FormatSchemaError(result CompareResult) string
- func GetCompiledRegex(pattern string) (*regexp.Regexp, error)
- func GetLocale() string
- func HasEmpty(elems []interface{}) (bool, int)
- func IfNullOrUndefined(str string) bool
- func IsAllEmpty(elems []interface{}) bool
- func IsAllowedField(field string, allowedFields ...[]string) bool
- func IsBase64(str string) bool
- func IsCEmpty[T comparable](v T) bool
- func IsEmail(email string) bool
- func IsEmptyAfterDeref(value interface{}) (interface{}, bool)
- func IsEmptyValue(v reflect.Value) bool
- func IsFuncType[T any]() bool
- func IsIP(ip string) bool
- func IsIPAllowed(ip string, cidrList []string) bool
- func IsIPBlocked(ip string, blacklist []string) bool
- func IsIPInRange(ip, start, end net.IP) bool
- func IsJSONColumnType(dbType string) bool
- func IsJSONNull(data []byte) bool
- func IsNil(x interface{}) bool
- func IsNull(str string) bool
- func IsPrivateIP(ip string) bool
- func IsSafeFieldName(field string) bool
- func IsTimeEmpty(t *time.Time) bool
- func IsTimeValid(timeVal interface{}) bool
- func IsUUID(uuid string) bool
- func IsUndefined(str string) bool
- func LookupJSONPath(data any, path string) (any, bool)
- func MatchIPInList(ip string, ipList []string) bool
- func MatchIPPattern(ip, pattern string) bool
- func MatchIPWithWildcard(ip, pattern string) bool
- func MatchPathInList(path string, patterns []string) bool
- func NewEnumValidator[T comparable](values ...T) *validate.EnumValidator[T]
- func NormalizeFilterValue(value interface{}) interface{}
- func NormalizeFilterValueIfNotEmpty(value interface{}) (interface{}, bool)
- func NormalizeFilterValueSlice(values []interface{}) []interface{}
- func RegisterI18n(locale string, key string, template string)
- func RegisterI18nMessages(locale string, messages map[string]string)
- func RegisterTranslation(locale string, tag string, template string)
- func RegisterTranslations(locale string, items map[string]string)
- func ScanJSONString(data []byte, start int) (int, error)
- func ScanJSONValueEnd(data []byte, start int) (int, error)
- func SetLocale(locale string)
- func SkipJSONSpaces(data []byte, i int) int
- func UnwrapProtobufWrapper(value interface{}) (interface{}, bool)
- func ValidateJSON(data []byte) error
- func ValidateJSONWithData(body []byte) (any, error)
- type CompareOperator
- type CompareResult
- func CompareNumbers[T Number](actual, expect T, op CompareOperator) CompareResult
- func CompareStrings(actual, expect string, op CompareOperator) CompareResult
- func ValidateBase64(str string) CompareResult
- func ValidateContains(body []byte, substring string) CompareResult
- func ValidateContentType(headers map[string]string, expected string) CompareResult
- func ValidateEmail(email string) CompareResult
- func ValidateHTTP(urlStr string) CompareResult
- func ValidateHeader(headers map[string]string, key, expected string, op CompareOperator) CompareResult
- func ValidateIP(ipStr string) CompareResult
- func ValidateIPAddress(ipStr string) CompareResult
- func ValidateJSONField(body []byte, field string, expected any) CompareResult
- func ValidateJSONFields(body []byte, rules map[string]any) []CompareResult
- func ValidateJSONPath(body []byte, jsonPath string, expected any, op CompareOperator) CompareResult
- func ValidateJSONPathExists(body []byte, jsonPath string) CompareResult
- func ValidateJSONSchema(data interface{}, s interface{}) CompareResult
- func ValidateNotContains(body []byte, substring string) CompareResult
- func ValidateProtocol(urlStr string, allowedProtocols ...string) CompareResult
- func ValidateRegex(body []byte, pattern string) CompareResult
- func ValidateStatusCode(statusCode, expected int, op CompareOperator) CompareResult
- func ValidateStatusCodeRange(actual, min, max int) CompareResult
- func ValidateString(actual, expect string, op CompareOperator) CompareResult
- func ValidateStructWithSchema(structData interface{}, s interface{}) CompareResult
- func ValidateUUID(uuidStr string) CompareResult
- func ValidateWebSocket(urlStr string) CompareResult
- type FieldError
- type FieldLevel
- type Func
- type FuncCtx
- type IPBase
- type IPSet
- type InvalidValidationError
- type JSONSchema
- type Number
- type Option
- type SchemaBuilder
- type TagNameFunc
- type Validate
- func (v *Validate) RegisterTagNameFunc(fn TagNameFunc)
- func (v *Validate) RegisterValidation(tag string, fn Func, _ ...bool) error
- func (v *Validate) RegisterValidationCtx(tag string, fn FuncCtx, _ ...bool) error
- func (v *Validate) SetTagName(name string)
- func (v *Validate) Struct(s interface{}) error
- func (v *Validate) StructCtx(ctx context.Context, s interface{}) error
- func (v *Validate) Var(field interface{}, tag string) error
- func (v *Validate) VarCtx(ctx context.Context, field interface{}, tag string) error
- type ValidationErrors
- type ValidationMessage
Constants ¶
const ( OpEqual = validate.OpEqual OpNotEqual = validate.OpNotEqual OpGreaterThan = validate.OpGreaterThan OpGreaterThanOrEqual = validate.OpGreaterThanOrEqual OpLessThan = validate.OpLessThan OpLessThanOrEqual = validate.OpLessThanOrEqual OpContains = validate.OpContains OpNotContains = validate.OpNotContains OpHasPrefix = validate.OpHasPrefix OpHasSuffix = validate.OpHasSuffix OpRegex = validate.OpRegex OpEmpty = validate.OpEmpty OpNotEmpty = validate.OpNotEmpty OpSymbolEqual = validate.OpSymbolEqual OpSymbolNotEqual = validate.OpSymbolNotEqual OpSymbolGreaterThan = validate.OpSymbolGreaterThan OpSymbolGreaterThanOrEqual = validate.OpSymbolGreaterThanOrEqual OpSymbolLessThan = validate.OpSymbolLessThan OpSymbolLessThanOrEqual = validate.OpSymbolLessThanOrEqual )
Variables ¶
This section is empty.
Functions ¶
func DerefValue ¶
func DerefValue(value interface{}) (interface{}, bool)
DerefValue 解开 interface 中的指针值
func EmptyToDefault ¶
EmptyToDefault 在字符串为空时返回默认值
func FormatSchemaError ¶
func FormatSchemaError(result CompareResult) string
FormatSchemaError 提取 schema 校验错误消息
func GetCompiledRegex ¶
GetCompiledRegex 获取编译的正则(带缓存)
func IfNullOrUndefined ¶
IfNullOrUndefined 判断字符串是否为 null 或 undefined
func IsAllowedField ¶
IsAllowedField 判断字段是否在白名单中
func IsEmptyAfterDeref ¶
func IsEmptyAfterDeref(value interface{}) (interface{}, bool)
IsEmptyAfterDeref 解引用后判断值是否为空
func IsJSONColumnType ¶
IsJSONColumnType 判断数据库列类型是否属于 JSON 类型
func LookupJSONPath ¶
LookupJSONPath 按轻量路径读取 JSON 数据
func MatchIPInList ¶
MatchIPInList 判断 IP 是否命中任意规则
func MatchIPWithWildcard ¶
MatchIPWithWildcard 使用星号通配符匹配 IPv4
func MatchPathInList ¶
MatchPathInList 判断路径是否命中任意路径前缀
func NewEnumValidator ¶
func NewEnumValidator[T comparable](values ...T) *validate.EnumValidator[T]
NewEnumValidator 创建枚举校验器
func NormalizeFilterValue ¶
func NormalizeFilterValue(value interface{}) interface{}
NormalizeFilterValue 归一化过滤值
func NormalizeFilterValueIfNotEmpty ¶
func NormalizeFilterValueIfNotEmpty(value interface{}) (interface{}, bool)
NormalizeFilterValueIfNotEmpty 过滤空值后返回归一化值
func NormalizeFilterValueSlice ¶
func NormalizeFilterValueSlice(values []interface{}) []interface{}
NormalizeFilterValueSlice 归一化过滤值切片
func RegisterI18n ¶
RegisterI18n 注册或覆盖某个语言下的单个 i18n 消息模板
func RegisterI18nMessages ¶
RegisterI18nMessages 批量注册某个语言下的 i18n 消息模板
func RegisterTranslation ¶
RegisterTranslation 注册或覆盖某个语言下的单个规则翻译模板
func RegisterTranslations ¶
RegisterTranslations 批量注册某个语言下的规则翻译模板
func ScanJSONString ¶
ScanJSONString 扫描 JSON 字符串,返回字符串结束后一位的位置
func ScanJSONValueEnd ¶
ScanJSONValueEnd 扫描任意 JSON 值,返回值结束后一位的位置
func UnwrapProtobufWrapper ¶
func UnwrapProtobufWrapper(value interface{}) (interface{}, bool)
UnwrapProtobufWrapper 通过反射解开 protobuf wrapper
func ValidateJSONWithData ¶
ValidateJSONWithData 校验 JSON 并返回反序列化数据
Types ¶
type CompareResult ¶
type CompareResult = validate.CompareResult
CompareResult 表示一次比较校验结果
func CompareNumbers ¶
func CompareNumbers[T Number](actual, expect T, op CompareOperator) CompareResult
CompareNumbers 比较两个数值
func CompareStrings ¶
func CompareStrings(actual, expect string, op CompareOperator) CompareResult
CompareStrings 比较两个字符串
func ValidateContains ¶
func ValidateContains(body []byte, substring string) CompareResult
ValidateContains 校验字节内容是否包含子串
func ValidateContentType ¶
func ValidateContentType(headers map[string]string, expected string) CompareResult
ValidateContentType 校验 Content-Type 是否包含期望类型
func ValidateHeader ¶
func ValidateHeader(headers map[string]string, key, expected string, op CompareOperator) CompareResult
ValidateHeader 根据操作符比较 Header 值
func ValidateIPAddress ¶
func ValidateIPAddress(ipStr string) CompareResult
ValidateIPAddress 校验 IP 地址格式
func ValidateJSONField ¶
func ValidateJSONField(body []byte, field string, expected any) CompareResult
ValidateJSONField 校验 JSON 顶层字段是否等于期望值
func ValidateJSONFields ¶
func ValidateJSONFields(body []byte, rules map[string]any) []CompareResult
ValidateJSONFields 批量校验 JSON 顶层字段
func ValidateJSONPath ¶
func ValidateJSONPath(body []byte, jsonPath string, expected any, op CompareOperator) CompareResult
ValidateJSONPath 校验 JSON 路径的值
func ValidateJSONPathExists ¶
func ValidateJSONPathExists(body []byte, jsonPath string) CompareResult
ValidateJSONPathExists 校验 JSON 路径是否存在
func ValidateJSONSchema ¶
func ValidateJSONSchema(data interface{}, s interface{}) CompareResult
ValidateJSONSchema 校验数据是否符合 schema
func ValidateNotContains ¶
func ValidateNotContains(body []byte, substring string) CompareResult
ValidateNotContains 校验字节内容是否不包含子串
func ValidateProtocol ¶
func ValidateProtocol(urlStr string, allowedProtocols ...string) CompareResult
ValidateProtocol 校验 URL 协议是否在允许列表中
func ValidateRegex ¶
func ValidateRegex(body []byte, pattern string) CompareResult
ValidateRegex 校验字节内容是否匹配正则表达式
func ValidateStatusCode ¶
func ValidateStatusCode(statusCode, expected int, op CompareOperator) CompareResult
ValidateStatusCode 比较 HTTP 状态码
func ValidateStatusCodeRange ¶
func ValidateStatusCodeRange(actual, min, max int) CompareResult
ValidateStatusCodeRange 校验 HTTP 状态码是否在闭区间内
func ValidateString ¶
func ValidateString(actual, expect string, op CompareOperator) CompareResult
ValidateString 校验字符串关系
func ValidateStructWithSchema ¶
func ValidateStructWithSchema(structData interface{}, s interface{}) CompareResult
ValidateStructWithSchema 校验结构体或 map 是否符合 schema
func ValidateWebSocket ¶
func ValidateWebSocket(urlStr string) CompareResult
ValidateWebSocket 校验 WebSocket URL
type FieldError ¶
type FieldError interface {
Tag() string
ActualTag() string
Namespace() string
StructNamespace() string
Field() string
StructField() string
Value() interface{}
Param() string
Kind() reflect.Kind
Type() reflect.Type
Error() string
}
FieldError 表示单个字段校验失败详情
type FieldLevel ¶
type FieldLevel interface {
Top() reflect.Value
Parent() reflect.Value
Field() reflect.Value
FieldName() string
StructFieldName() string
GetTag() string
Param() string
}
FieldLevel 为自定义规则提供当前字段、父结构和标签参数
type FuncCtx ¶
type FuncCtx func(ctx context.Context, fl FieldLevel) bool
FuncCtx 表示带 context 的自定义字段校验函数
type IPSet ¶
IPSet 表示预编译 IP 规则集合
func CompileIPSet ¶
CompileIPSet 将 IP 规则编译为可复用集合
func MustCompileIPSet ¶
MustCompileIPSet 编译 IP 规则,失败时 panic
type InvalidValidationError ¶
InvalidValidationError 表示传入校验器的参数类型不合法
func (*InvalidValidationError) Error ¶
func (e *InvalidValidationError) Error() string
type JSONSchema ¶
type JSONSchema = schema.JSONSchema
JSONSchema 描述 Argus 支持的 JSON Schema 子集
func QuickSchema ¶
func QuickSchema(properties map[string]string, required ...string) JSONSchema
QuickSchema 根据字段类型快速创建对象 schema
type Number ¶
type Number interface {
~int | ~int8 | ~int16 | ~int32 | ~int64 |
~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 | ~uintptr |
~float32 | ~float64
}
Number 表示可比较数值类型集合
type Option ¶
type Option func(*Validate)
Option 表示校验器初始化配置项
func WithPrivateFieldValidation ¶
func WithPrivateFieldValidation() Option
WithPrivateFieldValidation 保留私有字段校验选项,用于平滑迁移 go-playground 调用
func WithRequiredStructEnabled ¶
func WithRequiredStructEnabled() Option
WithRequiredStructEnabled 允许 required 对非指针结构体零值生效
type TagNameFunc ¶
type TagNameFunc func(field reflect.StructField) string
TagNameFunc 用于解析字段展示名,例如从 json tag 中取字段名
type Validate ¶
type Validate struct {
// contains filtered or unexported fields
}
Validate 是可复用且并发安全的校验器实例
func (*Validate) RegisterTagNameFunc ¶
func (v *Validate) RegisterTagNameFunc(fn TagNameFunc)
RegisterTagNameFunc 注册字段展示名解析函数
func (*Validate) RegisterValidation ¶
RegisterValidation 注册自定义字段校验函数
func (*Validate) RegisterValidationCtx ¶
RegisterValidationCtx 注册带 context 的自定义字段校验函数
func (*Validate) SetTagName ¶
SetTagName 设置校验标签名,默认使用 validate
type ValidationErrors ¶
type ValidationErrors []FieldError
ValidationErrors 表示字段校验失败集合
func (ValidationErrors) Error ¶
func (ve ValidationErrors) Error() string
func (ValidationErrors) MissingFields ¶
func (ve ValidationErrors) MissingFields() []string
MissingFields 返回 required 系列规则中缺失的字段名,字段名优先使用 json tag
func (ValidationErrors) RequiredMessages ¶
func (ve ValidationErrors) RequiredMessages(locale string) []ValidationMessage
RequiredMessages 只返回 required 系列规则产生的缺失字段错误
func (ValidationErrors) Translate ¶
func (ve ValidationErrors) Translate(locale string) []ValidationMessage
Translate 将 ValidationErrors 转换为数组化的 i18n 字段错误
type ValidationMessage ¶
type ValidationMessage struct {
Field string `json:"field"`
Namespace string `json:"namespace"`
StructField string `json:"struct_field,omitempty"`
StructNamespace string `json:"struct_namespace,omitempty"`
Tag string `json:"tag"`
ActualTag string `json:"actual_tag"`
Param string `json:"param,omitempty"`
Value interface{} `json:"value,omitempty"`
Message string `json:"message"`
}
ValidationMessage 表示一个可直接序列化给 HTTP/gRPC 网关的字段错误
func TranslateValidationErrors ¶
func TranslateValidationErrors(err error, locale string) []ValidationMessage
TranslateValidationErrors 将 error 转换为数组化的 i18n 字段错误
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package rule 提供 Argus 的标签规则、跨字段规则和时间表达式能力
|
Package rule 提供 Argus 的标签规则、跨字段规则和时间表达式能力 |
|
Package schema 提供轻量 JSON Schema 子集校验能力
|
Package schema 提供轻量 JSON Schema 子集校验能力 |
|
Package validate 承载从 go-toolbox/pkg/validator 迁移而来的通用校验能力
|
Package validate 承载从 go-toolbox/pkg/validator 迁移而来的通用校验能力 |