validate

package
v0.19.4 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 1, 2026 License: Apache-2.0, Apache-2.0 Imports: 25 Imported by: 1

Documentation

Overview

Package validate 承载从 go-toolbox/pkg/validator 迁移而来的通用校验能力

Index

Constants

View Source
const (
	// OpEqual 表示相等
	OpEqual = constants.OpEqual
	// OpNotEqual 表示不等
	OpNotEqual = constants.OpNotEqual
	// OpGreaterThan 表示大于
	OpGreaterThan = constants.OpGreaterThan
	// OpGreaterThanOrEqual 表示大于等于
	OpGreaterThanOrEqual = constants.OpGreaterThanOrEqual
	// OpLessThan 表示小于
	OpLessThan = constants.OpLessThan
	// OpLessThanOrEqual 表示小于等于
	OpLessThanOrEqual = constants.OpLessThanOrEqual
	// OpContains 表示包含
	OpContains = constants.OpContains
	// OpNotContains 表示不包含
	OpNotContains = constants.OpNotContains
	// OpHasPrefix 表示前缀匹配
	OpHasPrefix = constants.OpHasPrefix
	// OpHasSuffix 表示后缀匹配
	OpHasSuffix = constants.OpHasSuffix
	// OpRegex 表示正则匹配
	OpRegex = constants.OpRegex
	// OpEmpty 表示空字符串
	OpEmpty = constants.OpEmpty
	// OpNotEmpty 表示非空字符串
	OpNotEmpty = constants.OpNotEmpty

	// OpSymbolEqual 是相等操作符别名
	OpSymbolEqual = constants.OpSymbolEqual
	// OpSymbolNotEqual 是不等操作符别名
	OpSymbolNotEqual = constants.OpSymbolNotEqual
	// OpSymbolGreaterThan 是大于操作符别名
	OpSymbolGreaterThan = constants.OpSymbolGreaterThan
	// OpSymbolGreaterThanOrEqual 是大于等于操作符别名
	OpSymbolGreaterThanOrEqual = constants.OpSymbolGreaterThanOrEqual
	// OpSymbolLessThan 是小于操作符别名
	OpSymbolLessThan = constants.OpSymbolLessThan
	// OpSymbolLessThanOrEqual 是小于等于操作符别名
	OpSymbolLessThanOrEqual = constants.OpSymbolLessThanOrEqual
)
View Source
const (
	MsgCompareUnsupportedNumberOp = "compare.unsupported_number_op"
	MsgCompareNumberFailed        = "compare.number_failed"
	MsgCompareUnsupportedStringOp = "compare.unsupported_string_op"
	MsgCompareStringFailed        = "compare.string_failed"
	MsgCompareRegexCompileFailed  = "compare.regex_compile_failed"
	MsgCompareStatusOutOfRange    = "compare.status_out_of_range"
)

compare 系列消息键 —— 数值、字符串、状态码比较相关

View Source
const (
	MsgFormatRegexCompileFailed     = "format.regex_compile_failed"
	MsgFormatRegexNotMatched        = "format.regex_not_matched"
	MsgFormatEmailEmpty             = "format.email_empty"
	MsgFormatEmailInvalid           = "format.email_invalid"
	MsgFormatEmailMalformed         = "format.email_malformed"
	MsgFormatIPInvalid              = "format.ip_invalid"
	MsgFormatURLMissingProtocol     = "format.url_missing_protocol"
	MsgFormatURLUnsupportedProtocol = "format.url_unsupported_protocol"
	MsgFormatUUIDInvalid            = "format.uuid_invalid"
	MsgFormatBase64Empty            = "format.base64_empty"
	MsgFormatBase64Invalid          = "format.base64_invalid"
	MsgFormatSemverInvalid          = "format.semver_invalid"
	MsgFormatISBN10Invalid          = "format.isbn10_invalid"
	MsgFormatISBN13Invalid          = "format.isbn13_invalid"
	MsgFormatISSNInvalid            = "format.issn_invalid"
	MsgFormatBICInvalid             = "format.bic_invalid"
	MsgFormatCronInvalid            = "format.cron_invalid"
	MsgFormatDataURIInvalid         = "format.datauri_invalid"
	MsgFormatBCP47Invalid           = "format.bcp47_invalid"
	MsgFormatEthAddrInvalid         = "format.eth_addr_invalid"
	MsgFormatBtcAddrInvalid         = "format.btc_addr_invalid"
	MsgFormatImageInvalid           = "format.image_invalid"
	MsgFormatImageNotAllowed        = "format.image_format_not_allowed"
)

format 系列消息键 —— Email、IP、URL、UUID、Base64、正则格式校验相关

View Source
const (
	MsgJSONInvalid            = "json.invalid"
	MsgJSONRootNotObject      = "json.root_not_object"
	MsgJSONFieldNotFound      = "json.field_not_found"
	MsgJSONFieldValueMismatch = "json.field_value_mismatch"
	MsgJSONPathNotFound       = "json.path_not_found"
)

json 系列消息键 —— JSON 校验相关

View Source
const (
	MsgNetworkIPInvalid      = "network.ip_invalid"
	MsgNetworkIPRangeInvalid = "network.ip_range_invalid"
	MsgNetworkIPRuleInvalid  = "network.ip_rule_invalid"
)

network 系列消息键 —— 网络、IP、CIDR 校验相关

View Source
const (
	MsgSchemaEmpty              = "schema.empty"
	MsgSchemaTypeMismatch       = "schema.type_mismatch"
	MsgSchemaEnumMismatch       = "schema.enum_mismatch"
	MsgSchemaStringMinLength    = "schema.string_min_length"
	MsgSchemaStringMaxLength    = "schema.string_max_length"
	MsgSchemaNumberBelowMinimum = "schema.number_below_minimum"
	MsgSchemaNumberAboveMaximum = "schema.number_above_maximum"
	MsgSchemaFieldRequired      = "schema.field_required"
)

schema 系列消息键 —— JSON Schema 校验相关

View Source
const (
	CmpEQ  = constants.CmpEQ
	CmpLT  = constants.CmpLT
	CmpLTE = constants.CmpLTE
	CmpGT  = constants.CmpGT
	CmpGTE = constants.CmpGTE
	CmpNE  = constants.CmpNE
)
View Source
const (
	MsgEnumInvalidValue = "enum.invalid_value"
)

enum 系列消息键 —— 枚举校验相关

Variables

View Source
var (
	ColorHexRegex = regexp.MustCompile(`^#?([0-9a-fA-F]{3}|[0-9a-fA-F]{4}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})$`)
	RGBRegex      = regexp.MustCompile(
		`^rgb\(\s*(25[0-5]|2[0-4]\d|1?\d?\d)\s*,\s*(25[0-5]|2[0-4]\d|1?\d?\d)\s*,\s*(25[0-5]|2[0-4]\d|1?\d?\d)\s*\)$`,
	)
	RGBARegex = regexp.MustCompile(
		`^rgba\(\s*(25[0-5]|2[0-4]\d|1?\d?\d)\s*,\s*(25[0-5]|2[0-4]\d|1?\d?\d)\s*,\s*(25[0-5]|2[0-4]\d|1?\d?\d)\s*,\s*(0|1|0?\.\d+)\s*\)$`,
	)
	HSLRegex = regexp.MustCompile(
		`^hsl\(\s*(360|3[0-5]\d|[12]?\d?\d)\s*,\s*(100|[1-9]?\d)%\s*,\s*(100|[1-9]?\d)%\s*\)$`,
	)
	HSLARegex = regexp.MustCompile(
		`^hsla\(\s*(360|3[0-5]\d|[12]?\d?\d)\s*,\s*(100|[1-9]?\d)%\s*,\s*(100|[1-9]?\d)%\s*,\s*(0|1|0?\.\d+)\s*\)$`,
	)
	E164Regex     = regexp.MustCompile(`^\+[1-9]\d{1,14}$`)
	MongoIDRegex  = regexp.MustCompile(`^[0-9a-fA-F]{24}$`)
	DNSLabelRegex = regexp.MustCompile(`^[a-z]([-a-z0-9]*[a-z0-9])?$`)
)
View Source
var StringRuleMap = map[string]StringRuleFunc{}/* 113 elements not displayed */

StringRuleMap 字符串规则映射表,VarString 快速路径直接查表

Functions

func BytesValue

func BytesValue(field reflect.Value) ([]byte, bool)

func CalculateIDCardChecksum

func CalculateIDCardChecksum(id string) string

CalculateIDCardChecksum 计算给定17位身份证号的校验和字符

算法:

  1. 前17位数字分别乘以权重系数 [7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2]
  2. 求和后对11取模
  3. 根据模值查表得到校验码:[1,0,X,9,8,7,6,5,4,3,2]

性能:使用 ASCII 算术(char - '0'),按 byte 遍历,零分配

func ClearRegexCache

func ClearRegexCache()

ClearRegexCache 清空正则缓存

func CompareOp

func CompareOp(actual, expect float64, op constants.CmpOp) bool

func CompareStringsOp

func CompareStringsOp(left, right string, op constants.CmpOp) bool

func ContainsChinese

func ContainsChinese(s string) bool

ContainsChinese 判断字符串是否包含中文

func ContainsChineseChars

func ContainsChineseChars(s string) bool

ContainsChineseChars 检查字符串是否包含中文字符 注意:go-toolbox/pkg/argus 已有 ContainsChinese 函数(string_rules.go),此函数为其补充 如果只需判断是否包含中文,直接使用 validate.ContainsChinese

func ContainsQuotedNumber

func ContainsQuotedNumber(data []byte) bool

ContainsQuotedNumber 使用零分配字节扫描快速判断 JSON 中是否存在引号包裹的数字

该函数是高性能预检工具,在需要决定是否执行昂贵的 decode→convert→encode 流程前调用 识别模式(紧跟冒号/逗号/左中括号后的引号+数字/负号):

  • 键值对:`:"123` `:"-45`
  • 数组元素:`,"123` `,"-45` 或 `["123` `["-45`
  • 顶层字符串:整个 JSON 就是一个数字字符串如 `"123"`

性能特征:

  • 零堆分配、零内存拷贝,仅做字节级扫描
  • 小 JSON(< 200字节)通常在 20-100ns 内完成
  • 找到匹配模式后立即返回 true,无需扫描完整内容

注意:这是一个启发式预检,允许误报(会多做一次 decode)但绝不漏报(不会漏掉需要转换的情况)

参数:

  • data: JSON 字节切片

返回值:

  • bool: 是否存在引号包裹的数字字符串

func ConvertNumericStrings

func ConvertNumericStrings(data []byte) ([]byte, error)

ConvertNumericStrings 递归遍历 JSON 数据,将所有看起来像数字的字符串值自动转换为 json.Number 类型

适用场景:

  • 前端因 JavaScript Number 精度限制(最大安全整数 2^53-1),将 int64/uint64 以字符串形式传递;
  • 后端 protobuf/jsonpb 反序列化时期望收到数字类型,但实际收到的是字符串;
  • 需要做一次兼容转换,将数字字符串转为 JSON 数字,再交给后续的 protojson/encoding/json 解码

处理逻辑:

  • 对象(map):递归处理每个字段值;
  • 数组(slice):递归处理每个元素;
  • 字符串:尝试按 int64 → uint64 → float64 顺序解析,解析成功则转为 json.Number;
  • 其他类型(bool、number、null、已有的 json.Number)保持原样

安全策略:

  • 该函数只做语法层面的转换,不依赖任何 schema 信息;
  • 如果字符串无法解析为数字(如 "hello"、"ABC123"),保持原样不做处理;
  • 空字符串直接返回,不做转换;
  • 通过快速字节预检避免不必要的 decode/encode 开销

性能说明:

  • 当 JSON 中不存在引号包裹的数字时(常见场景),仅执行 O(n) 字节扫描,零堆分配;
  • 当存在数字字符串时,执行一次完整的 decode-convert-encode,开销约为 2x JSON 解析

参数:

  • data: 原始 JSON 字节切片

返回值:

  • []byte: 转换后的 JSON 字节切片;如果解析失败返回 nil 和 error
  • error: JSON 解析失败时返回错误

func ConvertNumericStringsRecursive

func ConvertNumericStringsRecursive(v interface{}) interface{}

convertNumericStringsRecursive 递归遍历 JSON 结构,将数字字符串转为 json.Number

func DerefReflect

func DerefReflect(v reflect.Value) reflect.Value

DerefReflect 解开指针和 interface,遇到 nil 返回无效 Value

拆成「可内联快路径 + 不可内联慢路径」:含 for 循环的函数编译器一律不内联, 而校验热路径上绝大多数字段是 string/int 等直接类型,一次「什么都不做」的解引用 也要付一次真实调用(3 字入参 + 3 字返回值的寄存器搬运与栈帧建立) 实测大结构体校验里这类空转调用约占总耗时 6%

无效 Value 的 flag 为 0,Kind() 返回 Invalid,走 default 原样返回—— 与原循环首轮 IsValid() 判定等价;Interface/Pointer 的 Kind 亦蕴含 IsValid

func DerefValue

func DerefValue(value any) (any, bool)

DerefValue 解开 interface 中的指针值

func DetectImageFormat

func DetectImageFormat(data []byte) string

DetectImageFormat 基于魔数嗅探图片格式,返回规范格式名,无法识别时返回空字符串 首字节分派将顺序魔数链收敛为单次跳转,仅检查魔数不校验完整性,完整性检查由各 Is 系列函数或 imageIntact 执行

func EmptyToDefault

func EmptyToDefault(str, defaultStr string) string

EmptyToDefault 在字符串为空时返回默认值

func GetCompiledRegex

func GetCompiledRegex(pattern string) (*regexp.Regexp, error)

GetCompiledRegex 获取编译的正则(带缓存)

func GetReflectKind

func GetReflectKind(value interface{}) reflect.Kind

GetReflectKind 获取任意值的 reflect.Kind

func HasDoubleByte

func HasDoubleByte(s string) bool

HasDoubleByte 检查字符串是否包含双字节字符(非 ASCII) 用于检测中文、日文、韩文等 CJK 字符

func HasEmpty

func HasEmpty(elems []any) (bool, int)

HasEmpty 判断切片中是否存在空值

func HasHostAfterScheme

func HasHostAfterScheme(s string, colonIdx int) bool

func HasLocalIP

func HasLocalIP(ip string) bool

HasLocalIP 判断 IP 字符串是否为本地或私有地址 包括:localhost、127.0.0.1、::1,以及 IPv4 私有地址段

func HasSchemeAndHost

func HasSchemeAndHost(s string) bool

func HasSpecialChars

func HasSpecialChars(s string) bool

HasSpecialChars 检查字符串是否包含特殊字符 特殊字符集合:!@#$%^&*()_+[]{}|;':",./<>?

func IfNullOrUndefined

func IfNullOrUndefined(str string) bool

IfNullOrUndefined 判断字符串是否为 null 或 undefined

func IsAVIF

func IsAVIF(data []byte) bool

IsAVIF 判断字节内容是否为有效的 AVIF 图片,基于 ftyp 容器的 major brand 判定

func IsAllChinese

func IsAllChinese(str string) (isAllChinese bool, nonChineseCount int)

IsAllChinese 检查字符串是否全部由汉字组成 返回值:isAllChinese 表示是否全为汉字,nonChineseCount 表示非汉字字符数

func IsAllEmpty

func IsAllEmpty(elems []any) bool

IsAllEmpty 判断切片中所有元素是否都为空

func IsAllowedField

func IsAllowedField(field string, allowedFields ...[]string) bool

IsAllowedField 判断字段是否在白名单中,未传白名单时退化为安全字段名检查

func IsAlpha

func IsAlpha(s string) bool

IsAlpha 检查字符串是否全部由英文字母组成(大小写不限)

func IsAlphanumeric

func IsAlphanumeric(s string) bool

IsAlphanumeric 检查字符串是否由数字和英文字母组成

func IsBCP47

func IsBCP47(tag string) bool

func IsBIC

func IsBIC(bic string) bool

func IsBMP

func IsBMP(data []byte) bool

IsBMP 判断字节内容是否为有效的 BMP 图片,DIB 头大小必须为已知合法值

func IsBase64

func IsBase64(str string) bool

IsBase64 判断字符串是否为有效 Base64

func IsBlankString

func IsBlankString(s string) bool

IsBlankString 检查字符串是否为空

func IsBtcAddr

func IsBtcAddr(addr string) bool

func IsCEmpty

func IsCEmpty[T comparable](v T) bool

IsCEmpty 判断可比较值是否为零值

func IsChineseIDCard

func IsChineseIDCard(s string) bool

IsChineseIDCard 检查字符串是否为有效的大陆身份证号(15位或18位) 18位身份证包含校验位,15位身份证不包含校验位

func IsChineseIDCardWithChecksum

func IsChineseIDCardWithChecksum(s string) bool

IsChineseIDCardWithChecksum 检查18位身份证号(含校验位验证) 比仅检查格式更严格:会计算校验和并验证最后一位

func IsChinesePhoneNumber

func IsChinesePhoneNumber(s string) bool

IsChinesePhoneNumber 检查字符串是否为有效的大陆手机号 规则:长度11位 + 首位为1 + 第二位为3-9 + 其余为数字

func IsCron

func IsCron(expr string) bool

func IsDataURI

func IsDataURI(uri string) bool

func IsDecimalMN

func IsDecimalMN(s string, m, n int) bool

IsDecimalMN 检查字符串是否为有 m 到 n 位小数的正实数

func IsDecimalN

func IsDecimalN(s string, n int) bool

IsDecimalN 检查字符串是否为有 n 位小数的正实数 规则:整数部分 + . + n 位小数(或无小数部分)

func IsDigits

func IsDigits(s string) bool

IsDigits 检查字符串是否全部由数字组成(空串返回 true)

func IsDigitsLengthGeN

func IsDigitsLengthGeN(s string, n int) bool

IsDigitsLengthGeN 检查字符串是否为长度不小于 n 的纯数字

func IsDigitsLengthMN

func IsDigitsLengthMN(s string, m, n int) bool

IsDigitsLengthMN 检查字符串是否为长度在 m 到 n 之间的纯数字

func IsDigitsLengthN

func IsDigitsLengthN(s string, n int) bool

IsDigitsLengthN 检查字符串是否为长度等于 n 的纯数字

func IsDocumentationAddress

func IsDocumentationAddress(ip net.IP) bool

IsDocumentationAddress 检查 IP 是否为文档专用地址 IPv6 文档地址前缀:2001:db8::/32

func IsEmail

func IsEmail(email string) bool

IsEmail 判断字符串是否为有效 Email

func IsEmptyAfterDeref

func IsEmptyAfterDeref(value any) (any, bool)

IsEmptyAfterDeref 解引用后判断值是否为空,适合 SQL/query 过滤条件

func IsEmptyLine

func IsEmptyLine(s string) bool

IsEmptyLine 检查字符串是否为空白行(全部由空白字符组成)

func IsEmptyValue

func IsEmptyValue(v reflect.Value) bool

IsEmptyValue 判断 reflect.Value 是否为空值

func IsEmptyValueWithStruct

func IsEmptyValueWithStruct(v reflect.Value, requiredStructEnabled bool) bool

IsEmptyValueWithStruct 判断 reflect.Value 是否为空值,并允许控制结构体零值语义

func IsEthAddr

func IsEthAddr(addr string) bool

func IsFilterScalarKind

func IsFilterScalarKind(kind reflect.Kind) bool

IsFilterScalarKind 判断 Kind 是否属于过滤场景下的标量类型(bool/number)

func IsFuncType

func IsFuncType[T any]() bool

IsFuncType 判断泛型类型是否为函数

func IsGIF

func IsGIF(data []byte) bool

IsGIF 判断字节内容是否为完整的 GIF 图片,尾部必须为流结束符 0x3B

func IsGlobalUnicast

func IsGlobalUnicast(ip string) bool

IsGlobalUnicast 检查 IP 字符串是否为全球单播地址 排除:私有地址、回环、链路本地、文档地址等

func IsHEIC

func IsHEIC(data []byte) bool

IsHEIC 判断字节内容是否为有效的 HEIC/HEIF 图片,基于 ftyp 容器的 major brand 判定

func IsHex

func IsHex(s string) bool

IsHex 检查字符串是否为有效的十六进制数

func IsHexChar

func IsHexChar(c byte) bool

func IsHostTerminator

func IsHostTerminator(c byte) bool

func IsHostname

func IsHostname(host string) bool

IsHostname 判断字符串是否为合法 hostname(零正则、零分配)

func IsICO

func IsICO(data []byte) bool

IsICO 判断字节内容是否为有效的 ICO 图标,目录项数量必须大于 0

func IsIP

func IsIP(ip string) bool

IsIP 判断字符串是否为有效 IP

func IsIPAllowed

func IsIPAllowed(ip string, cidrList []string) bool

IsIPAllowed 判断 IP 是否在允许列表中,空列表表示允许所有

func IsIPBlocked

func IsIPBlocked(ip string, blacklist []string) bool

IsIPBlocked 判断 IP 是否在黑名单中,空列表表示不阻止

func IsIPInRange

func IsIPInRange(ip, start, end net.IP) bool

IsIPInRange 判断 IPv4 地址是否落在闭区间内

func IsISBN10

func IsISBN10(isbn string) bool

func IsISBN10CheckDigit

func IsISBN10CheckDigit(c byte, sum int) bool

func IsISBN13

func IsISBN13(isbn string) bool

func IsISSN

func IsISSN(issn string) bool

func IsImage

func IsImage(data []byte) bool

IsImage 判断字节内容是否为有效且完整的图片(任意支持格式)

func IsImageInFormats

func IsImageInFormats(data []byte, formats string) bool

IsImageInFormats 判断字节内容是否为白名单内的有效图片 formats 为空格分隔的格式名,出现未知格式名时直接失败(fail-closed)

func IsIntOrFloat

func IsIntOrFloat(s string) bool

IsIntOrFloat 检查字符串是否为整数或最多2位小数 规则:至少1位整数 + 可选小数点 + 0~2位小数

func IsJPEG

func IsJPEG(data []byte) bool

IsJPEG 判断字节内容是否为完整的 JPEG 图片,后缀必须为 EOI 标记以排除中缀含 EOI 的截断文件

func IsJSONColumnType

func IsJSONColumnType(dbType string) bool

IsJSONColumnType 判断数据库列类型是否属于 JSON 类型

func IsJSONNull

func IsJSONNull(data []byte) bool

IsJSONNull 判断 JSON 字节是否为 null

func IsJSONSpace

func IsJSONSpace(c byte) bool

IsJSONSpace 判断字节是否是 JSON 空白字符

根据 RFC 8259,JSON 中合法的空白字符为:空格(0x20)、水平制表符(0x09)、 换行符(0x0A)、回车符(0x0D)

func IsLengthN

func IsLengthN(s string, n int) bool

IsLengthN 检查字符串的 rune 长度是否等于 n 注意:按 rune 计数,非 byte 长度

func IsLinkLocalIP

func IsLinkLocalIP(ip net.IP) bool

IsLinkLocalIP 检查 IP 是否为链路本地地址 IPv4: 169.254.0.0/16 IPv6: fe80::/10

func IsLowerAlpha

func IsLowerAlpha(s string) bool

IsLowerAlpha 检查字符串是否全部由小写英文字母组成

func IsLuhnChecksum

func IsLuhnChecksum(s string) bool

func IsNegativeNonZeroInt

func IsNegativeNonZeroInt(s string) bool

IsNegativeNonZeroInt 检查字符串是否为负整数(首位非零) 规则:\-[1-9][0-9]*

func IsNil

func IsNil(x any) bool

IsNil 判断 interface 是否为 nil 或内部持有 nil

func IsNilValue

func IsNilValue(v reflect.Value) bool

IsNilValue 判断 reflect.Value 是否为 nil

func IsNonZeroLeadingDigits

func IsNonZeroLeadingDigits(s string) bool

IsNonZeroLeadingDigits 检查字符串是否为非零开头的纯数字

func IsNull

func IsNull(str string) bool

IsNull 判断字符串是否为 null

func IsNumStart

func IsNumStart(c byte) bool

IsNumStart 判断字节是否是数字字符串的起始字符

合法的数字起始字符包括:

  • '-':负数开头(如 "-123"、"-3.14")
  • '+':正数开头(如 "+123",部分 JSON5 扩展支持)
  • '0'-'9':阿拉伯数字

参数:

  • c: 待判断的字节

返回值:

  • bool: 是否可以作为数字(字符串形式)的起始字符

func IsPNG

func IsPNG(data []byte) bool

IsPNG 判断字节内容是否为完整的 PNG 图片,魔数后必须存在 IEND 尾块

func IsPasswordPattern

func IsPasswordPattern(s string, m, n int) bool

IsPasswordPattern 检查密码是否符合规则: 以英文字母开头,由字母、数字、下划线组成,长度在 m 到 n 之间

func IsPositiveNonZeroInt

func IsPositiveNonZeroInt(s string) bool

IsPositiveNonZeroInt 检查字符串是否为正整数(可选+前缀,首位非零) 规则:\+?[1-9][0-9]*

func IsPrivateIP

func IsPrivateIP(ip string) bool

IsPrivateIP 判断 IP 是否属于常见私有或本地地址段

func IsSVG

func IsSVG(data []byte) bool

IsSVG 判断字节内容是否为有效的 SVG 文档 状态机嗅探:跳过 BOM、空白、<?xml…?>、<!--…-->、<!DOCTYPE…?> 后必须紧跟 <svg,全部扫描限制在文件头部

func IsSafeFieldName

func IsSafeFieldName(field string) bool

IsSafeFieldName 判断字段名是否只包含字母、数字、下划线和点号

func IsSemver

func IsSemver(version string) bool

func IsStrongPassword

func IsStrongPassword(s string) bool

IsStrongPassword 检查密码强度:

  • 长度至少 8 个字符
  • 包含至少一个小写字母
  • 包含至少一个大写字母
  • 包含至少一个数字
  • 包含至少一个特殊字符

使用手动字节扫描,一次遍历检查所有字符类别,零分配

func IsTIFF

func IsTIFF(data []byte) bool

IsTIFF 判断字节内容是否为有效的 TIFF 图片,支持 II 与 MM 两种字节序

func IsTimeEmpty

func IsTimeEmpty(t *time.Time) bool

IsTimeEmpty 判断时间是否为空或早于 Unix epoch

func IsTimeFormat

func IsTimeFormat(s string) bool

IsTimeFormat 校验时间格式

func IsTimeType

func IsTimeType(t reflect.Type) bool

func IsTimeValid

func IsTimeValid(timeVal any) bool

IsTimeValid 判断时间值是否有效,非时间类型视为有效以兼容过滤场景

func IsTrueString

func IsTrueString(s string) bool

IsTrueString 判断字符串是否表示 true(true/1/yes,大小写不敏感) 使用 strings.EqualFold 避免分配

func IsUUID

func IsUUID(uuid string) bool

IsUUID 判断字符串是否为有效 UUID

长度确定为 36 后分隔符位置即为常量,故先一次性比四个位置,再分五段扫十六进制。 原实现每个字符都要走一遍 switch i 的 4 路位置判定,profile 里这一句 独占 IsUUID 自身耗时的 41%(270ms/660ms),而它对 32 个数据字符全是空耗。

判定结果与逐字符版本完全一致,只是失败时先报分隔符还是先报非法字符的 先后不同——本函数只返回 bool,该顺序不可观测

func IsUndefined

func IsUndefined(str string) bool

IsUndefined 判断字符串是否为 undefined

func IsUniqueLocalAddress

func IsUniqueLocalAddress(ip net.IP) bool

IsUniqueLocalAddress 检查 IP 是否为 IPv6 唯一本地地址(ULA) ULA 范围:fc00::/7(包含 fc00::/8 和 fd00::/8)

func IsUpperAlpha

func IsUpperAlpha(s string) bool

IsUpperAlpha 检查字符串是否全部由大写英文字母组成

func IsValidCronField

func IsValidCronField(field string) bool

func IsValidHostChar

func IsValidHostChar(s string, hostStart, i int) bool

func IsValidJSONBytes

func IsValidJSONBytes(data []byte) bool

func IsValidJSONString

func IsValidJSONString(s string) bool

func IsWebP

func IsWebP(data []byte) bool

IsWebP 判断字节内容是否为有效的 WebP 图片,RIFF 容器内必须为 VP8/VP8L/VP8X 载荷

func IsWholeNumber

func IsWholeNumber(f float64) bool

IsWholeNumber 判断 float64 是否为整数(whole number)

用于 RuleInteger 规则:float 类型字段必须为整数值

实现说明:

  • 使用 math.Trunc 而非 int64 转换,避免大数溢出 int64 转换在 |f| > math.MaxInt64 时会返回错误结果(溢出) math.Trunc 直接操作 float64 的尾数位,无溢出风险,支持全 float64 范围
  • 显式排除 NaN 和 Inf NaN:math.Trunc(NaN) = NaN,但 NaN != NaN,所以会被误判为非整数(巧合正确) Inf:math.Trunc(+Inf) = +Inf,+Inf == +Inf 为 true,需显式排除

性能:2 次比较(IsNaN/IsInf)+ 1 次 Trunc + 1 次比较,无分配 相比 int64 转换版本:性能相当,但精度完整,无溢出风险

func IsWordChars

func IsWordChars(s string) bool

IsWordChars 检查字符串是否由字母、数字、下划线组成(\w+)

func LookupJSONPath

func LookupJSONPath(data any, path string) (any, bool)

LookupJSONPath 按轻量路径读取 JSON 数据,支持 $.a.b、a.b、items[0].name

func LuhnDouble

func LuhnDouble(n int) int

func MatchIPInList

func MatchIPInList(ip string, ipList []string) bool

MatchIPInList 判断 IP 是否命中任意规则

func MatchIPPattern

func MatchIPPattern(ip, pattern string) bool

MatchIPPattern 判断 IP 是否命中单个规则

func MatchIPWithWildcard

func MatchIPWithWildcard(ip, pattern string) bool

MatchIPWithWildcard 使用星号通配符匹配 IPv4

func MatchPathGlob

func MatchPathGlob(path, pattern string) bool

MatchPathGlob Glob 模式匹配路径(支持 * 和 ? 通配符)

func MatchPathInList

func MatchPathInList(path string, patterns []string) bool

MatchPathInList 判断路径是否命中任意路径规则

func MatchStringRunes

func MatchStringRunes(field reflect.Value, fn func(rune) bool) bool

func NormalizeFilterValue

func NormalizeFilterValue(value any) any

NormalizeFilterValue 归一化过滤值,支持 protobuf wrapper、protobuf enum 和任意切片

func NormalizeFilterValueIfNotEmpty

func NormalizeFilterValueIfNotEmpty(value any) (any, bool)

NormalizeFilterValueIfNotEmpty 过滤空值后返回归一化值

func NormalizeFilterValueSlice

func NormalizeFilterValueSlice(values []any) []any

NormalizeFilterValueSlice 归一化过滤值切片

func NormalizeImageFormat

func NormalizeImageFormat(name string) (string, bool)

NormalizeImageFormat 归一化图片格式名,忽略大小写且 jpg 等价 jpeg,未知格式名返回 false 与白名单解析共用 imageFormatTokenBit 的机器字归一比较,避免两套匹配逻辑并存

func NumericValue

func NumericValue(field reflect.Value) (float64, bool)

func ParseFloat

func ParseFloat(s string) (float64, bool)

func ParseMonth

func ParseMonth(month string) (time.Month, error)

ParseMonth 解析月份字段,返回 time.Month

支持格式:

  • 数字:1-12
  • 缩写:JAN, FEB, MAR, APR, MAY, JUN, JUL, AUG, SEP, OCT, NOV, DEC
  • 全称:JANUARY, FEBRUARY, MARCH, APRIL, MAY, JUNE, JULY, AUGUST, SEPTEMBER, OCTOBER, NOVEMBER, DECEMBER

func ParseSemverBuildMeta

func ParseSemverBuildMeta(s string, pos *int) bool

func ParseSemverNum

func ParseSemverNum(s string, pos *int) bool

func ParseSemverPreRelease

func ParseSemverPreRelease(s string, pos *int) bool

func ParseWeek

func ParseWeek(week string) (time.Weekday, error)

ParseWeek 解析星期字段,返回 time.Weekday

支持格式:

  • 数字:0-6(0=Sunday)
  • 缩写:M/MON, T/TUE, W/WED, R/THU, F/FRI, S/SAT, U/SUN
  • 全称:MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY

func ScalarString

func ScalarString(field reflect.Value) (string, bool)

func ScanJSONString

func ScanJSONString(data []byte, start int) (int, error)

ScanJSONString 扫描 JSON 字符串,并返回字符串结束后一位的位置

func ScanJSONValueEnd

func ScanJSONValueEnd(data []byte, start int) (int, error)

ScanJSONValueEnd 扫描任意 JSON 值,并返回值结束后一位的位置

func SkipJSONSpaces

func SkipJSONSpaces(data []byte, i int) int

SkipJSONSpaces 跳过 JSON 字节流中的空白字符,并返回下一个非空白位置

func StringASCII

func StringASCII(s string) bool

func StringAlpha

func StringAlpha(s string) bool

func StringAlphaSpace

func StringAlphaSpace(s string) bool

func StringAlphaUnicode

func StringAlphaUnicode(s string) bool

func StringAlphanum

func StringAlphanum(s string) bool

func StringAlphanumSpace

func StringAlphanumSpace(s string) bool

func StringAlphanumUnicode

func StringAlphanumUnicode(s string) bool

func StringBCP47

func StringBCP47(s string) bool

StringBCP47 验证 BCP47 语言标签

func StringBIC

func StringBIC(s string) bool

StringBIC 验证 BIC/SWIFT 代码

func StringBase32

func StringBase32(s string) bool

func StringBase64

func StringBase64(s string) bool

func StringBase64RawURL

func StringBase64RawURL(s string) bool

func StringBase64URL

func StringBase64URL(s string) bool

func StringBoolean

func StringBoolean(s string) bool

func StringBtcAddr

func StringBtcAddr(s string) bool

StringBtcAddr 验证比特币地址

func StringCIDR

func StringCIDR(s string) bool

func StringCIDRv4

func StringCIDRv4(s string) bool

func StringCIDRv6

func StringCIDRv6(s string) bool

func StringCompareLength

func StringCompareLength(s, param string, op constants.CmpOp) bool

func StringContains

func StringContains(s, param string) bool

func StringContainsAny

func StringContainsAny(s, param string) bool

func StringContainsRune

func StringContainsRune(s, param string) bool

func StringCron

func StringCron(s string) bool

StringCron 验证 cron 表达式

func StringDNSRFC1035Label

func StringDNSRFC1035Label(s string) bool

StringDNSRFC1035Label 校验 RFC 1035 标签,等价于 `len<=63 && ^[a-z]([-a-z0-9]*[a-z0-9])?$`

原实现走 DNSLabelRegex.MatchString,单次匹配 105ns;手写扫描约 10ns

func StringDataURI

func StringDataURI(s string) bool

StringDataURI 验证 Data URI 格式

func StringDatetime

func StringDatetime(s, param string) bool

func StringDir

func StringDir(s string) bool

func StringDirPath

func StringDirPath(s string) bool

func StringE164

func StringE164(s string) bool

func StringEndsNotWith

func StringEndsNotWith(s, param string) bool

func StringEndsWith

func StringEndsWith(s, param string) bool

func StringEq

func StringEq(s, param string) bool

func StringEqIgnoreCase

func StringEqIgnoreCase(s, param string) bool

func StringEthAddr

func StringEthAddr(s string) bool

StringEthAddr 验证以太坊地址

func StringExcludes

func StringExcludes(s, param string) bool

func StringExcludesAll

func StringExcludesAll(s, param string) bool

func StringExcludesRune

func StringExcludesRune(s, param string) bool

func StringFQDN

func StringFQDN(s string) bool

func StringFile

func StringFile(s string) bool

func StringFilePath

func StringFilePath(s string) bool

func StringGt

func StringGt(s, param string) bool

func StringGte

func StringGte(s, param string) bool

func StringHSL

func StringHSL(s string) bool

func StringHSLA

func StringHSLA(s string) bool

func StringHTML

func StringHTML(s string) bool

func StringHTMLEncoded

func StringHTMLEncoded(s string) bool

func StringHTTPSURL

func StringHTTPSURL(s string) bool

func StringHTTPURL

func StringHTTPURL(s string) bool

func StringHexColor

func StringHexColor(s string) bool

func StringHexadecimal

func StringHexadecimal(s string) bool

func StringHostname

func StringHostname(s string) bool

func StringHostnamePort

func StringHostnamePort(s string) bool

func StringIP

func StringIP(s string) bool

func StringIPv4

func StringIPv4(s string) bool

func StringIPv6

func StringIPv6(s string) bool

func StringISSN

func StringISSN(s string) bool

StringISSN 验证 ISSN 格式

func StringInteger

func StringInteger(s string) bool

StringInteger 判断字符串是否表示一个整数

支持格式:

  • "123" → true
  • "-123" → true
  • "+123" → true
  • "0" → true
  • "12.3" → false(含小数点)
  • "12a" → false(含非数字字符)
  • "" → false(空字符串)
  • "+" → false(只有符号)
  • " 123" → false(含空格,需调用方先 TrimSpace)

性能:手动字节扫描,零分配 相比 strconv.ParseFloat(s, 64) 节省:

  • 1 次 float64 解析
  • 1 次 error 对象分配
  • 1 次 strings.Contains 等辅助调用

func StringIsDefault

func StringIsDefault(s string) bool

func StringJSON

func StringJSON(s string) bool

func StringLatitude

func StringLatitude(s string) bool

func StringLen

func StringLen(s, param string) bool

func StringLongitude

func StringLongitude(s string) bool

func StringLowercase

func StringLowercase(s string) bool

func StringLt

func StringLt(s, param string) bool

func StringLte

func StringLte(s, param string) bool

func StringMAC

func StringMAC(s string) bool

func StringMatchRunes

func StringMatchRunes(s string, fn func(rune) bool) bool

func StringMax

func StringMax(s, param string) bool

func StringMin

func StringMin(s, param string) bool

func StringMongoDB

func StringMongoDB(s string) bool

StringMongoDB 校验 MongoDB ObjectID,等价于 `^[0-9a-fA-F]{24}$`

原实现走 MongoIDRegex.MatchString:定长 + 单一字符类的模式交给正则引擎, 单次匹配 119ns,而同形状的手写扫描(见 StringAlpha 一族)只要约 10ns

func StringMultibyte

func StringMultibyte(s string) bool

func StringNe

func StringNe(s, param string) bool

func StringNeIgnoreCase

func StringNeIgnoreCase(s, param string) bool

func StringNumber

func StringNumber(s string) bool

func StringOneOf

func StringOneOf(s string, parts []string) bool

StringOneOf 判断字符串是否在候选列表中(精确匹配)

func StringOneOfCI

func StringOneOfCI(s string, parts []string) bool

StringOneOfCI 判断字符串是否在候选列表中(忽略大小写)

func StringPort

func StringPort(s string) bool

func StringPrintASCII

func StringPrintASCII(s string) bool

func StringRGB

func StringRGB(s string) bool

func StringRGBA

func StringRGBA(s string) bool

func StringRequired

func StringRequired(s string) bool

StringRequired 检查字符串是否为空

func StringStartsNotWith

func StringStartsNotWith(s, param string) bool

func StringStartsWith

func StringStartsWith(s, param string) bool

func StringTimezone

func StringTimezone(s string) bool

func StringURI

func StringURI(s string) bool

func StringURL

func StringURL(s string) bool

func StringURLEncoded

func StringURLEncoded(s string) bool

func StringUUID

func StringUUID(s string) bool

func StringUUID3

func StringUUID3(s string) bool

func StringUUID4

func StringUUID4(s string) bool

func StringUUID5

func StringUUID5(s string) bool

func StringUnique

func StringUnique(s string) bool

func StringUppercase

func StringUppercase(s string) bool

func StringValue

func StringValue(v reflect.Value) string

StringValue 将 reflect.Value 转为字符串

func StringValueFromField

func StringValueFromField(field reflect.Value) (string, bool)

func TrimSpaceIfNeeded

func TrimSpaceIfNeeded(s string) string

func TryStringToNumber

func TryStringToNumber(s string) interface{}

TryStringToNumber 尝试将字符串解析为数字,成功则返回 json.Number,失败则返回原字符串 解析顺序:先尝试 int64(有符号整数),再尝试 uint64(无符号大整数),最后尝试 float64(浮点数)

func UnwrapProtobufEnum

func UnwrapProtobufEnum(value any) (any, bool)

UnwrapProtobufEnum 通过反射解开 protobuf enum,避免引入 protobuf 依赖 protobuf enum 具有 Number() 方法,返回 protoreflect.EnumNumber(即 int32) 必须转换为基础数值类型,否则 ClickHouse 等驱动会调用 String() 方法序列化为枚举名(如 "LOGIN_RESULT_STATUS_FAILURE")导致 TYPE_MISMATCH

func UnwrapProtobufWrapper

func UnwrapProtobufWrapper(value any) (any, bool)

UnwrapProtobufWrapper 通过反射解开 protobuf wrapper,避免引入 protobuf 依赖

func ValidateJSON

func ValidateJSON(data []byte) error

ValidateJSON 校验 JSON 字节是否有效

func ValidateJSONWithData

func ValidateJSONWithData(body []byte) (any, error)

ValidateJSONWithData 校验 JSON 并返回反序列化数据

Types

type CmpOp

type CmpOp = constants.CmpOp

func CmpOpFromStr

func CmpOpFromStr(op string) CmpOp

type CompareOperator

type CompareOperator = constants.CompareOperator

CompareOperator 表示通用比较操作符

type CompareResult

type CompareResult struct {
	Success bool   `json:"success"`
	Message string `json:"message"`
	Actual  string `json:"actual"`
	Expect  string `json:"expect"`
}

CompareResult 表示一次比较校验结果

func CompareNumbers

func CompareNumbers[T Number](actual, expect T, op constants.CompareOperator) CompareResult

CompareNumbers 比较两个数值

func CompareStrings

func CompareStrings(actual, expect string, op constants.CompareOperator) CompareResult

CompareStrings 比较两个字符串

func ValidateBCP47

func ValidateBCP47(tag string) CompareResult

func ValidateBIC

func ValidateBIC(bic string) CompareResult

func ValidateBase64

func ValidateBase64(str string) CompareResult

ValidateBase64 校验 Base64 字符串

func ValidateBtcAddr

func ValidateBtcAddr(addr string) CompareResult

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 ValidateCron

func ValidateCron(expr string) CompareResult

func ValidateDataURI

func ValidateDataURI(uri string) CompareResult

func ValidateEmail

func ValidateEmail(email string) CompareResult

ValidateEmail 校验 Email 格式

func ValidateEthAddr

func ValidateEthAddr(addr string) CompareResult

func ValidateHTTP

func ValidateHTTP(urlStr string) CompareResult

ValidateHTTP 校验 HTTP/HTTPS URL

func ValidateHeader

func ValidateHeader(headers map[string]string, key, expected string, op constants.CompareOperator) CompareResult

ValidateHeader 根据操作符比较 Header 值

func ValidateIP

func ValidateIP(ipStr string) CompareResult

ValidateIP 校验 IP 地址格式(ValidateIPAddress 的别名,兼容旧 API)

func ValidateIPAddress

func ValidateIPAddress(ipStr string) CompareResult

ValidateIPAddress 校验 IP 地址格式

func ValidateISBN10

func ValidateISBN10(isbn string) CompareResult

func ValidateISBN13

func ValidateISBN13(isbn string) CompareResult

func ValidateISSN

func ValidateISSN(issn string) CompareResult

func ValidateImage

func ValidateImage(data []byte) CompareResult

ValidateImage 校验字节内容是否为有效且完整的图片

func ValidateImageInFormats

func ValidateImageInFormats(data []byte, formats string) CompareResult

ValidateImageInFormats 校验字节内容是否为白名单内的有效图片 白名单非法时快速失败,不再对字节内容执行嗅探

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 constants.CompareOperator) CompareResult

ValidateJSONPath 校验 JSON 路径的值

func ValidateJSONPathExists

func ValidateJSONPathExists(body []byte, jsonPath string) CompareResult

ValidateJSONPathExists 校验 JSON 路径是否存在

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 ValidateSemver

func ValidateSemver(version string) CompareResult

func ValidateStatusCode

func ValidateStatusCode(statusCode, expected int, op constants.CompareOperator) CompareResult

ValidateStatusCode 比较 HTTP 状态码

func ValidateStatusCodeRange

func ValidateStatusCodeRange(actual, min, max int) CompareResult

ValidateStatusCodeRange 校验 HTTP 状态码是否在闭区间内

func ValidateString

func ValidateString(actual, expect string, op constants.CompareOperator) CompareResult

ValidateString 校验字符串关系,保留 go-toolbox 旧函数名

func ValidateUUID

func ValidateUUID(uuidStr string) CompareResult

ValidateUUID 校验 UUID 格式

func ValidateWebSocket

func ValidateWebSocket(urlStr string) CompareResult

ValidateWebSocket 校验 WebSocket URL

type EnumValidator

type EnumValidator[T comparable] struct {
	// contains filtered or unexported fields
}

EnumValidator 表示一组可校验的枚举值

func NewEnumValidator

func NewEnumValidator[T comparable](values ...T) *EnumValidator[T]

NewEnumValidator 创建枚举校验器

func (*EnumValidator[T]) Add

func (v *EnumValidator[T]) Add(values ...T)

Add 增加枚举值

func (*EnumValidator[T]) Clear

func (v *EnumValidator[T]) Clear()

Clear 清空枚举集合

func (*EnumValidator[T]) Clone

func (v *EnumValidator[T]) Clone() *EnumValidator[T]

Clone 复制枚举校验器

func (*EnumValidator[T]) Contains

func (v *EnumValidator[T]) Contains(value T) bool

Contains 判断值是否存在于枚举集合

func (*EnumValidator[T]) Count

func (v *EnumValidator[T]) Count() int

Count 返回枚举值数量

func (*EnumValidator[T]) GetValidValues

func (v *EnumValidator[T]) GetValidValues() []T

GetValidValues 返回枚举值列表

func (*EnumValidator[T]) GetValidValuesString

func (v *EnumValidator[T]) GetValidValuesString() []string

GetValidValuesString 返回枚举值字符串列表

func (*EnumValidator[T]) IsValid

func (v *EnumValidator[T]) IsValid(value T) bool

IsValid 判断值是否属于枚举集合

func (*EnumValidator[T]) MustBeValid

func (v *EnumValidator[T]) MustBeValid(value T) error

MustBeValid 校验值是否属于枚举集合,失败时返回错误

func (*EnumValidator[T]) Remove

func (v *EnumValidator[T]) Remove(values ...T)

Remove 删除枚举值

type IPBase

type IPBase struct{}

IPBase 提供面向对象风格的 IP 校验入口,兼容 go-toolbox 旧 API

func (*IPBase) ValidateIP

func (b *IPBase) ValidateIP(ip string) error

ValidateIP 校验 IP 字符串是否有效

type IPSet

type IPSet struct {
	// contains filtered or unexported fields
}

IPSet 表示预编译 IP 规则集合,适合高频请求路径复用

func CompileIPSet

func CompileIPSet(patterns []string) (*IPSet, error)

CompileIPSet 将 IP 规则编译为可复用集合

func MustCompileIPSet

func MustCompileIPSet(patterns []string) *IPSet

MustCompileIPSet 编译 IP 规则,失败时 panic,适合初始化阶段使用

func (*IPSet) Contains

func (set *IPSet) Contains(ip string) bool

Contains 判断 IP 是否命中规则集合

type Number

type Number interface {
	~int | ~int8 | ~int16 | ~int32 | ~int64 |
		~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 | ~uintptr |
		~float32 | ~float64
}

Number 表示可比较数值类型集合

type StringRuleFunc

type StringRuleFunc func(s, param string) bool

StringRuleFunc 字符串规则函数签名

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL