Documentation
¶
Overview ¶
Package validate 承载从 go-toolbox/pkg/validator 迁移而来的通用校验能力
Index ¶
- Constants
- Variables
- func BytesValue(field reflect.Value) ([]byte, bool)
- func CalculateIDCardChecksum(id string) string
- func ClearRegexCache()
- func CompareOp(actual, expect float64, op constants.CmpOp) bool
- func CompareStringsOp(left, right string, op constants.CmpOp) bool
- func ContainsChinese(s string) bool
- func ContainsChineseChars(s string) bool
- func ContainsQuotedNumber(data []byte) bool
- func ConvertNumericStrings(data []byte) ([]byte, error)
- func ConvertNumericStringsRecursive(v interface{}) interface{}
- func DerefReflect(v reflect.Value) reflect.Value
- func DerefValue(value any) (any, bool)
- func DetectImageFormat(data []byte) string
- func EmptyToDefault(str, defaultStr string) string
- func GetCompiledRegex(pattern string) (*regexp.Regexp, error)
- func GetReflectKind(value interface{}) reflect.Kind
- func HasDoubleByte(s string) bool
- func HasEmpty(elems []any) (bool, int)
- func HasHostAfterScheme(s string, colonIdx int) bool
- func HasLocalIP(ip string) bool
- func HasSchemeAndHost(s string) bool
- func HasSpecialChars(s string) bool
- func IfNullOrUndefined(str string) bool
- func IsAVIF(data []byte) bool
- func IsAllChinese(str string) (isAllChinese bool, nonChineseCount int)
- func IsAllEmpty(elems []any) bool
- func IsAllowedField(field string, allowedFields ...[]string) bool
- func IsAlpha(s string) bool
- func IsAlphanumeric(s string) bool
- func IsBCP47(tag string) bool
- func IsBIC(bic string) bool
- func IsBMP(data []byte) bool
- func IsBase64(str string) bool
- func IsBlankString(s string) bool
- func IsBtcAddr(addr string) bool
- func IsCEmpty[T comparable](v T) bool
- func IsChineseIDCard(s string) bool
- func IsChineseIDCardWithChecksum(s string) bool
- func IsChinesePhoneNumber(s string) bool
- func IsCron(expr string) bool
- func IsDataURI(uri string) bool
- func IsDecimalMN(s string, m, n int) bool
- func IsDecimalN(s string, n int) bool
- func IsDigits(s string) bool
- func IsDigitsLengthGeN(s string, n int) bool
- func IsDigitsLengthMN(s string, m, n int) bool
- func IsDigitsLengthN(s string, n int) bool
- func IsDocumentationAddress(ip net.IP) bool
- func IsEmail(email string) bool
- func IsEmptyAfterDeref(value any) (any, bool)
- func IsEmptyLine(s string) bool
- func IsEmptyValue(v reflect.Value) bool
- func IsEmptyValueWithStruct(v reflect.Value, requiredStructEnabled bool) bool
- func IsEthAddr(addr string) bool
- func IsFilterScalarKind(kind reflect.Kind) bool
- func IsFuncType[T any]() bool
- func IsGIF(data []byte) bool
- func IsGlobalUnicast(ip string) bool
- func IsHEIC(data []byte) bool
- func IsHex(s string) bool
- func IsHexChar(c byte) bool
- func IsHostTerminator(c byte) bool
- func IsHostname(host string) bool
- func IsICO(data []byte) 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 IsISBN10(isbn string) bool
- func IsISBN10CheckDigit(c byte, sum int) bool
- func IsISBN13(isbn string) bool
- func IsISSN(issn string) bool
- func IsImage(data []byte) bool
- func IsImageInFormats(data []byte, formats string) bool
- func IsIntOrFloat(s string) bool
- func IsJPEG(data []byte) bool
- func IsJSONColumnType(dbType string) bool
- func IsJSONNull(data []byte) bool
- func IsJSONSpace(c byte) bool
- func IsLengthN(s string, n int) bool
- func IsLinkLocalIP(ip net.IP) bool
- func IsLowerAlpha(s string) bool
- func IsLuhnChecksum(s string) bool
- func IsNegativeNonZeroInt(s string) bool
- func IsNil(x any) bool
- func IsNilValue(v reflect.Value) bool
- func IsNonZeroLeadingDigits(s string) bool
- func IsNull(str string) bool
- func IsNumStart(c byte) bool
- func IsPNG(data []byte) bool
- func IsPasswordPattern(s string, m, n int) bool
- func IsPositiveNonZeroInt(s string) bool
- func IsPrivateIP(ip string) bool
- func IsSVG(data []byte) bool
- func IsSafeFieldName(field string) bool
- func IsSemver(version string) bool
- func IsStrongPassword(s string) bool
- func IsTIFF(data []byte) bool
- func IsTimeEmpty(t *time.Time) bool
- func IsTimeFormat(s string) bool
- func IsTimeType(t reflect.Type) bool
- func IsTimeValid(timeVal any) bool
- func IsTrueString(s string) bool
- func IsUUID(uuid string) bool
- func IsUndefined(str string) bool
- func IsUniqueLocalAddress(ip net.IP) bool
- func IsUpperAlpha(s string) bool
- func IsValidCronField(field string) bool
- func IsValidHostChar(s string, hostStart, i int) bool
- func IsValidJSONBytes(data []byte) bool
- func IsValidJSONString(s string) bool
- func IsWebP(data []byte) bool
- func IsWholeNumber(f float64) bool
- func IsWordChars(s string) bool
- func LookupJSONPath(data any, path string) (any, bool)
- func LuhnDouble(n int) int
- func MatchIPInList(ip string, ipList []string) bool
- func MatchIPPattern(ip, pattern string) bool
- func MatchIPWithWildcard(ip, pattern string) bool
- func MatchPathGlob(path, pattern string) bool
- func MatchPathInList(path string, patterns []string) bool
- func MatchStringRunes(field reflect.Value, fn func(rune) bool) bool
- func NormalizeFilterValue(value any) any
- func NormalizeFilterValueIfNotEmpty(value any) (any, bool)
- func NormalizeFilterValueSlice(values []any) []any
- func NormalizeImageFormat(name string) (string, bool)
- func NumericValue(field reflect.Value) (float64, bool)
- func ParseFloat(s string) (float64, bool)
- func ParseMonth(month string) (time.Month, error)
- func ParseSemverBuildMeta(s string, pos *int) bool
- func ParseSemverNum(s string, pos *int) bool
- func ParseSemverPreRelease(s string, pos *int) bool
- func ParseWeek(week string) (time.Weekday, error)
- func ScalarString(field reflect.Value) (string, bool)
- func ScanJSONString(data []byte, start int) (int, error)
- func ScanJSONValueEnd(data []byte, start int) (int, error)
- func SkipJSONSpaces(data []byte, i int) int
- func StringASCII(s string) bool
- func StringAlpha(s string) bool
- func StringAlphaSpace(s string) bool
- func StringAlphaUnicode(s string) bool
- func StringAlphanum(s string) bool
- func StringAlphanumSpace(s string) bool
- func StringAlphanumUnicode(s string) bool
- func StringBCP47(s string) bool
- func StringBIC(s string) bool
- func StringBase32(s string) bool
- func StringBase64(s string) bool
- func StringBase64RawURL(s string) bool
- func StringBase64URL(s string) bool
- func StringBoolean(s string) bool
- func StringBtcAddr(s string) bool
- func StringCIDR(s string) bool
- func StringCIDRv4(s string) bool
- func StringCIDRv6(s string) bool
- func StringCompareLength(s, param string, op constants.CmpOp) bool
- func StringContains(s, param string) bool
- func StringContainsAny(s, param string) bool
- func StringContainsRune(s, param string) bool
- func StringCron(s string) bool
- func StringDNSRFC1035Label(s string) bool
- func StringDataURI(s string) bool
- func StringDatetime(s, param string) bool
- func StringDir(s string) bool
- func StringDirPath(s string) bool
- func StringE164(s string) bool
- func StringEndsNotWith(s, param string) bool
- func StringEndsWith(s, param string) bool
- func StringEq(s, param string) bool
- func StringEqIgnoreCase(s, param string) bool
- func StringEthAddr(s string) bool
- func StringExcludes(s, param string) bool
- func StringExcludesAll(s, param string) bool
- func StringExcludesRune(s, param string) bool
- func StringFQDN(s string) bool
- func StringFile(s string) bool
- func StringFilePath(s string) bool
- func StringGt(s, param string) bool
- func StringGte(s, param string) bool
- func StringHSL(s string) bool
- func StringHSLA(s string) bool
- func StringHTML(s string) bool
- func StringHTMLEncoded(s string) bool
- func StringHTTPSURL(s string) bool
- func StringHTTPURL(s string) bool
- func StringHexColor(s string) bool
- func StringHexadecimal(s string) bool
- func StringHostname(s string) bool
- func StringHostnamePort(s string) bool
- func StringIP(s string) bool
- func StringIPv4(s string) bool
- func StringIPv6(s string) bool
- func StringISSN(s string) bool
- func StringInteger(s string) bool
- func StringIsDefault(s string) bool
- func StringJSON(s string) bool
- func StringLatitude(s string) bool
- func StringLen(s, param string) bool
- func StringLongitude(s string) bool
- func StringLowercase(s string) bool
- func StringLt(s, param string) bool
- func StringLte(s, param string) bool
- func StringMAC(s string) bool
- func StringMatchRunes(s string, fn func(rune) bool) bool
- func StringMax(s, param string) bool
- func StringMin(s, param string) bool
- func StringMongoDB(s string) bool
- func StringMultibyte(s string) bool
- func StringNe(s, param string) bool
- func StringNeIgnoreCase(s, param string) bool
- func StringNumber(s string) bool
- func StringOneOf(s string, parts []string) bool
- func StringOneOfCI(s string, parts []string) bool
- func StringPort(s string) bool
- func StringPrintASCII(s string) bool
- func StringRGB(s string) bool
- func StringRGBA(s string) bool
- func StringRequired(s string) bool
- func StringStartsNotWith(s, param string) bool
- func StringStartsWith(s, param string) bool
- func StringTimezone(s string) bool
- func StringURI(s string) bool
- func StringURL(s string) bool
- func StringURLEncoded(s string) bool
- func StringUUID(s string) bool
- func StringUUID3(s string) bool
- func StringUUID4(s string) bool
- func StringUUID5(s string) bool
- func StringUnique(s string) bool
- func StringUppercase(s string) bool
- func StringValue(v reflect.Value) string
- func StringValueFromField(field reflect.Value) (string, bool)
- func TrimSpaceIfNeeded(s string) string
- func TryStringToNumber(s string) interface{}
- func UnwrapProtobufEnum(value any) (any, bool)
- func UnwrapProtobufWrapper(value any) (any, bool)
- func ValidateJSON(data []byte) error
- func ValidateJSONWithData(body []byte) (any, error)
- type CmpOp
- type CompareOperator
- type CompareResult
- func CompareNumbers[T Number](actual, expect T, op constants.CompareOperator) CompareResult
- func CompareStrings(actual, expect string, op constants.CompareOperator) CompareResult
- func ValidateBCP47(tag string) CompareResult
- func ValidateBIC(bic string) CompareResult
- func ValidateBase64(str string) CompareResult
- func ValidateBtcAddr(addr string) CompareResult
- func ValidateContains(body []byte, substring string) CompareResult
- func ValidateContentType(headers map[string]string, expected string) CompareResult
- func ValidateCron(expr string) CompareResult
- func ValidateDataURI(uri string) CompareResult
- func ValidateEmail(email string) CompareResult
- func ValidateEthAddr(addr string) CompareResult
- func ValidateHTTP(urlStr string) CompareResult
- func ValidateHeader(headers map[string]string, key, expected string, op constants.CompareOperator) CompareResult
- func ValidateIP(ipStr string) CompareResult
- func ValidateIPAddress(ipStr string) CompareResult
- func ValidateISBN10(isbn string) CompareResult
- func ValidateISBN13(isbn string) CompareResult
- func ValidateISSN(issn string) CompareResult
- func ValidateImage(data []byte) CompareResult
- func ValidateImageInFormats(data []byte, formats 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 constants.CompareOperator) CompareResult
- func ValidateJSONPathExists(body []byte, jsonPath string) CompareResult
- func ValidateNotContains(body []byte, substring string) CompareResult
- func ValidateProtocol(urlStr string, allowedProtocols ...string) CompareResult
- func ValidateRegex(body []byte, pattern string) CompareResult
- func ValidateSemver(version string) CompareResult
- func ValidateStatusCode(statusCode, expected int, op constants.CompareOperator) CompareResult
- func ValidateStatusCodeRange(actual, min, max int) CompareResult
- func ValidateString(actual, expect string, op constants.CompareOperator) CompareResult
- func ValidateUUID(uuidStr string) CompareResult
- func ValidateWebSocket(urlStr string) CompareResult
- type EnumValidator
- func (v *EnumValidator[T]) Add(values ...T)
- func (v *EnumValidator[T]) Clear()
- func (v *EnumValidator[T]) Clone() *EnumValidator[T]
- func (v *EnumValidator[T]) Contains(value T) bool
- func (v *EnumValidator[T]) Count() int
- func (v *EnumValidator[T]) GetValidValues() []T
- func (v *EnumValidator[T]) GetValidValuesString() []string
- func (v *EnumValidator[T]) IsValid(value T) bool
- func (v *EnumValidator[T]) MustBeValid(value T) error
- func (v *EnumValidator[T]) Remove(values ...T)
- type IPBase
- type IPSet
- type Number
- type StringRuleFunc
Constants ¶
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 )
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 系列消息键 —— 数值、字符串、状态码比较相关
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、正则格式校验相关
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 校验相关
const ( MsgNetworkIPInvalid = "network.ip_invalid" MsgNetworkIPRangeInvalid = "network.ip_range_invalid" MsgNetworkIPRuleInvalid = "network.ip_rule_invalid" )
network 系列消息键 —— 网络、IP、CIDR 校验相关
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 校验相关
const ( CmpEQ = constants.CmpEQ CmpLT = constants.CmpLT CmpLTE = constants.CmpLTE CmpGT = constants.CmpGT CmpGTE = constants.CmpGTE CmpNE = constants.CmpNE )
const (
MsgEnumInvalidValue = "enum.invalid_value"
)
enum 系列消息键 —— 枚举校验相关
Variables ¶
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])?$`) )
var StringRuleMap = map[string]StringRuleFunc{}/* 113 elements not displayed */
StringRuleMap 字符串规则映射表,VarString 快速路径直接查表
Functions ¶
func CalculateIDCardChecksum ¶
CalculateIDCardChecksum 计算给定17位身份证号的校验和字符
算法:
- 前17位数字分别乘以权重系数 [7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2]
- 求和后对11取模
- 根据模值查表得到校验码:[1,0,X,9,8,7,6,5,4,3,2]
性能:使用 ASCII 算术(char - '0'),按 byte 遍历,零分配
func ContainsChineseChars ¶
ContainsChineseChars 检查字符串是否包含中文字符 注意:go-toolbox/pkg/argus 已有 ContainsChinese 函数(string_rules.go),此函数为其补充 如果只需判断是否包含中文,直接使用 validate.ContainsChinese
func ContainsQuotedNumber ¶
ContainsQuotedNumber 使用零分配字节扫描快速判断 JSON 中是否存在引号包裹的数字
该函数是高性能预检工具,在需要决定是否执行昂贵的 decode→convert→encode 流程前调用 识别模式(紧跟冒号/逗号/左中括号后的引号+数字/负号):
- 键值对:`:"123` `:"-45`
- 数组元素:`,"123` `,"-45` 或 `["123` `["-45`
- 顶层字符串:整个 JSON 就是一个数字字符串如 `"123"`
性能特征:
- 零堆分配、零内存拷贝,仅做字节级扫描
- 小 JSON(< 200字节)通常在 20-100ns 内完成
- 找到匹配模式后立即返回 true,无需扫描完整内容
注意:这是一个启发式预检,允许误报(会多做一次 decode)但绝不漏报(不会漏掉需要转换的情况)
参数:
- data: JSON 字节切片
返回值:
- bool: 是否存在引号包裹的数字字符串
func ConvertNumericStrings ¶
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 ¶
DerefReflect 解开指针和 interface,遇到 nil 返回无效 Value
拆成「可内联快路径 + 不可内联慢路径」:含 for 循环的函数编译器一律不内联, 而校验热路径上绝大多数字段是 string/int 等直接类型,一次「什么都不做」的解引用 也要付一次真实调用(3 字入参 + 3 字返回值的寄存器搬运与栈帧建立) 实测大结构体校验里这类空转调用约占总耗时 6%
无效 Value 的 flag 为 0,Kind() 返回 Invalid,走 default 原样返回—— 与原循环首轮 IsValid() 判定等价;Interface/Pointer 的 Kind 亦蕴含 IsValid
func DetectImageFormat ¶
DetectImageFormat 基于魔数嗅探图片格式,返回规范格式名,无法识别时返回空字符串 首字节分派将顺序魔数链收敛为单次跳转,仅检查魔数不校验完整性,完整性检查由各 Is 系列函数或 imageIntact 执行
func EmptyToDefault ¶
EmptyToDefault 在字符串为空时返回默认值
func GetCompiledRegex ¶
GetCompiledRegex 获取编译的正则(带缓存)
func GetReflectKind ¶
GetReflectKind 获取任意值的 reflect.Kind
func HasDoubleByte ¶
HasDoubleByte 检查字符串是否包含双字节字符(非 ASCII) 用于检测中文、日文、韩文等 CJK 字符
func HasHostAfterScheme ¶
func HasLocalIP ¶
HasLocalIP 判断 IP 字符串是否为本地或私有地址 包括:localhost、127.0.0.1、::1,以及 IPv4 私有地址段
func HasSchemeAndHost ¶
func HasSpecialChars ¶
HasSpecialChars 检查字符串是否包含特殊字符 特殊字符集合:!@#$%^&*()_+[]{}|;':",./<>?
func IfNullOrUndefined ¶
IfNullOrUndefined 判断字符串是否为 null 或 undefined
func IsAllChinese ¶
IsAllChinese 检查字符串是否全部由汉字组成 返回值:isAllChinese 表示是否全为汉字,nonChineseCount 表示非汉字字符数
func IsAllowedField ¶
IsAllowedField 判断字段是否在白名单中,未传白名单时退化为安全字段名检查
func IsChineseIDCard ¶
IsChineseIDCard 检查字符串是否为有效的大陆身份证号(15位或18位) 18位身份证包含校验位,15位身份证不包含校验位
func IsChineseIDCardWithChecksum ¶
IsChineseIDCardWithChecksum 检查18位身份证号(含校验位验证) 比仅检查格式更严格:会计算校验和并验证最后一位
func IsChinesePhoneNumber ¶
IsChinesePhoneNumber 检查字符串是否为有效的大陆手机号 规则:长度11位 + 首位为1 + 第二位为3-9 + 其余为数字
func IsDecimalN ¶
IsDecimalN 检查字符串是否为有 n 位小数的正实数 规则:整数部分 + . + n 位小数(或无小数部分)
func IsDigitsLengthGeN ¶
IsDigitsLengthGeN 检查字符串是否为长度不小于 n 的纯数字
func IsDigitsLengthMN ¶
IsDigitsLengthMN 检查字符串是否为长度在 m 到 n 之间的纯数字
func IsDigitsLengthN ¶
IsDigitsLengthN 检查字符串是否为长度等于 n 的纯数字
func IsDocumentationAddress ¶
IsDocumentationAddress 检查 IP 是否为文档专用地址 IPv6 文档地址前缀:2001:db8::/32
func IsEmptyAfterDeref ¶
IsEmptyAfterDeref 解引用后判断值是否为空,适合 SQL/query 过滤条件
func IsEmptyValueWithStruct ¶
IsEmptyValueWithStruct 判断 reflect.Value 是否为空值,并允许控制结构体零值语义
func IsFilterScalarKind ¶
IsFilterScalarKind 判断 Kind 是否属于过滤场景下的标量类型(bool/number)
func IsGlobalUnicast ¶
IsGlobalUnicast 检查 IP 字符串是否为全球单播地址 排除:私有地址、回环、链路本地、文档地址等
func IsHostTerminator ¶
func IsIPAllowed ¶
IsIPAllowed 判断 IP 是否在允许列表中,空列表表示允许所有
func IsIPBlocked ¶
IsIPBlocked 判断 IP 是否在黑名单中,空列表表示不阻止
func IsISBN10CheckDigit ¶
func IsImageInFormats ¶
IsImageInFormats 判断字节内容是否为白名单内的有效图片 formats 为空格分隔的格式名,出现未知格式名时直接失败(fail-closed)
func IsIntOrFloat ¶
IsIntOrFloat 检查字符串是否为整数或最多2位小数 规则:至少1位整数 + 可选小数点 + 0~2位小数
func IsJSONColumnType ¶
IsJSONColumnType 判断数据库列类型是否属于 JSON 类型
func IsJSONSpace ¶
IsJSONSpace 判断字节是否是 JSON 空白字符
根据 RFC 8259,JSON 中合法的空白字符为:空格(0x20)、水平制表符(0x09)、 换行符(0x0A)、回车符(0x0D)
func IsLinkLocalIP ¶
IsLinkLocalIP 检查 IP 是否为链路本地地址 IPv4: 169.254.0.0/16 IPv6: fe80::/10
func IsLuhnChecksum ¶
func IsNegativeNonZeroInt ¶
IsNegativeNonZeroInt 检查字符串是否为负整数(首位非零) 规则:\-[1-9][0-9]*
func IsNonZeroLeadingDigits ¶
IsNonZeroLeadingDigits 检查字符串是否为非零开头的纯数字
func IsNumStart ¶
IsNumStart 判断字节是否是数字字符串的起始字符
合法的数字起始字符包括:
- '-':负数开头(如 "-123"、"-3.14")
- '+':正数开头(如 "+123",部分 JSON5 扩展支持)
- '0'-'9':阿拉伯数字
参数:
- c: 待判断的字节
返回值:
- bool: 是否可以作为数字(字符串形式)的起始字符
func IsPasswordPattern ¶
IsPasswordPattern 检查密码是否符合规则: 以英文字母开头,由字母、数字、下划线组成,长度在 m 到 n 之间
func IsPositiveNonZeroInt ¶
IsPositiveNonZeroInt 检查字符串是否为正整数(可选+前缀,首位非零) 规则:\+?[1-9][0-9]*
func IsSVG ¶
IsSVG 判断字节内容是否为有效的 SVG 文档 状态机嗅探:跳过 BOM、空白、<?xml…?>、<!--…-->、<!DOCTYPE…?> 后必须紧跟 <svg,全部扫描限制在文件头部
func IsSafeFieldName ¶
IsSafeFieldName 判断字段名是否只包含字母、数字、下划线和点号
func IsStrongPassword ¶
IsStrongPassword 检查密码强度:
- 长度至少 8 个字符
- 包含至少一个小写字母
- 包含至少一个大写字母
- 包含至少一个数字
- 包含至少一个特殊字符
使用手动字节扫描,一次遍历检查所有字符类别,零分配
func IsTimeType ¶
func IsTrueString ¶
IsTrueString 判断字符串是否表示 true(true/1/yes,大小写不敏感) 使用 strings.EqualFold 避免分配
func IsUUID ¶
IsUUID 判断字符串是否为有效 UUID
长度确定为 36 后分隔符位置即为常量,故先一次性比四个位置,再分五段扫十六进制。 原实现每个字符都要走一遍 switch i 的 4 路位置判定,profile 里这一句 独占 IsUUID 自身耗时的 41%(270ms/660ms),而它对 32 个数据字符全是空耗。
判定结果与逐字符版本完全一致,只是失败时先报分隔符还是先报非法字符的 先后不同——本函数只返回 bool,该顺序不可观测
func IsUniqueLocalAddress ¶
IsUniqueLocalAddress 检查 IP 是否为 IPv6 唯一本地地址(ULA) ULA 范围:fc00::/7(包含 fc00::/8 和 fd00::/8)
func IsValidCronField ¶
func IsValidHostChar ¶
func IsValidJSONBytes ¶
func IsValidJSONString ¶
func IsWholeNumber ¶
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 LookupJSONPath ¶
LookupJSONPath 按轻量路径读取 JSON 数据,支持 $.a.b、a.b、items[0].name
func LuhnDouble ¶
func MatchIPInList ¶
MatchIPInList 判断 IP 是否命中任意规则
func MatchIPWithWildcard ¶
MatchIPWithWildcard 使用星号通配符匹配 IPv4
func MatchPathGlob ¶
MatchPathGlob Glob 模式匹配路径(支持 * 和 ? 通配符)
func MatchPathInList ¶
MatchPathInList 判断路径是否命中任意路径规则
func NormalizeFilterValue ¶
NormalizeFilterValue 归一化过滤值,支持 protobuf wrapper、protobuf enum 和任意切片
func NormalizeFilterValueIfNotEmpty ¶
NormalizeFilterValueIfNotEmpty 过滤空值后返回归一化值
func NormalizeFilterValueSlice ¶
NormalizeFilterValueSlice 归一化过滤值切片
func NormalizeImageFormat ¶
NormalizeImageFormat 归一化图片格式名,忽略大小写且 jpg 等价 jpeg,未知格式名返回 false 与白名单解析共用 imageFormatTokenBit 的机器字归一比较,避免两套匹配逻辑并存
func ParseFloat ¶
func ParseMonth ¶
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 ParseSemverNum ¶
func ParseSemverPreRelease ¶
func ParseWeek ¶
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 ScanJSONString ¶
ScanJSONString 扫描 JSON 字符串,并返回字符串结束后一位的位置
func ScanJSONValueEnd ¶
ScanJSONValueEnd 扫描任意 JSON 值,并返回值结束后一位的位置
func SkipJSONSpaces ¶
SkipJSONSpaces 跳过 JSON 字节流中的空白字符,并返回下一个非空白位置
func StringASCII ¶
func StringAlpha ¶
func StringAlphaSpace ¶
func StringAlphaUnicode ¶
func StringAlphanum ¶
func StringAlphanumSpace ¶
func StringAlphanumUnicode ¶
func StringBase32 ¶
func StringBase64 ¶
func StringBase64RawURL ¶
func StringBase64URL ¶
func StringBoolean ¶
func StringCIDR ¶
func StringCIDRv4 ¶
func StringCIDRv6 ¶
func StringContains ¶
func StringContainsAny ¶
func StringContainsRune ¶
func StringDNSRFC1035Label ¶
StringDNSRFC1035Label 校验 RFC 1035 标签,等价于 `len<=63 && ^[a-z]([-a-z0-9]*[a-z0-9])?$`
原实现走 DNSLabelRegex.MatchString,单次匹配 105ns;手写扫描约 10ns
func StringDatetime ¶
func StringDirPath ¶
func StringE164 ¶
func StringEndsNotWith ¶
func StringEndsWith ¶
func StringEqIgnoreCase ¶
func StringExcludes ¶
func StringExcludesAll ¶
func StringExcludesRune ¶
func StringFQDN ¶
func StringFile ¶
func StringFilePath ¶
func StringHSLA ¶
func StringHTML ¶
func StringHTMLEncoded ¶
func StringHTTPSURL ¶
func StringHTTPURL ¶
func StringHexColor ¶
func StringHexadecimal ¶
func StringHostname ¶
func StringHostnamePort ¶
func StringIPv4 ¶
func StringIPv6 ¶
func StringInteger ¶
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 StringJSON ¶
func StringLatitude ¶
func StringLongitude ¶
func StringLowercase ¶
func StringMongoDB ¶
StringMongoDB 校验 MongoDB ObjectID,等价于 `^[0-9a-fA-F]{24}$`
原实现走 MongoIDRegex.MatchString:定长 + 单一字符类的模式交给正则引擎, 单次匹配 119ns,而同形状的手写扫描(见 StringAlpha 一族)只要约 10ns
func StringMultibyte ¶
func StringNeIgnoreCase ¶
func StringNumber ¶
func StringOneOfCI ¶
StringOneOfCI 判断字符串是否在候选列表中(忽略大小写)
func StringPort ¶
func StringPrintASCII ¶
func StringRGBA ¶
func StringStartsNotWith ¶
func StringStartsWith ¶
func StringTimezone ¶
func StringURLEncoded ¶
func StringUUID ¶
func StringUUID3 ¶
func StringUUID4 ¶
func StringUUID5 ¶
func StringUnique ¶
func StringUppercase ¶
func TrimSpaceIfNeeded ¶
func TryStringToNumber ¶
func TryStringToNumber(s string) interface{}
TryStringToNumber 尝试将字符串解析为数字,成功则返回 json.Number,失败则返回原字符串 解析顺序:先尝试 int64(有符号整数),再尝试 uint64(无符号大整数),最后尝试 float64(浮点数)
func UnwrapProtobufEnum ¶
UnwrapProtobufEnum 通过反射解开 protobuf enum,避免引入 protobuf 依赖 protobuf enum 具有 Number() 方法,返回 protoreflect.EnumNumber(即 int32) 必须转换为基础数值类型,否则 ClickHouse 等驱动会调用 String() 方法序列化为枚举名(如 "LOGIN_RESULT_STATUS_FAILURE")导致 TYPE_MISMATCH
func UnwrapProtobufWrapper ¶
UnwrapProtobufWrapper 通过反射解开 protobuf wrapper,避免引入 protobuf 依赖
func ValidateJSONWithData ¶
ValidateJSONWithData 校验 JSON 并返回反序列化数据
Types ¶
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 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 ValidateEthAddr ¶
func ValidateEthAddr(addr string) CompareResult
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 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 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]) Contains ¶
func (v *EnumValidator[T]) Contains(value T) bool
Contains 判断值是否存在于枚举集合
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 校验值是否属于枚举集合,失败时返回错误
type IPSet ¶
type IPSet struct {
// contains filtered or unexported fields
}
IPSet 表示预编译 IP 规则集合,适合高频请求路径复用
func CompileIPSet ¶
CompileIPSet 将 IP 规则编译为可复用集合
func MustCompileIPSet ¶
MustCompileIPSet 编译 IP 规则,失败时 panic,适合初始化阶段使用