validator

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: 18 Imported by: 1

README

⚡ Argus

Zero-dependency · High-performance · i18n-native Go struct validator

Go Reference Go Report Card Coverage License

English · 中文


✨ Features

  • 🚀 Zero third-party dependencies — Only Go standard library, supply-chain secure
  • ⚡ Zero-reflection VarString fast path — String variable validation bypasses reflect entirely, 0 heap allocations, 2~3× faster than reflection path
  • 🏷️ 126 built-in field rules — required, min/max, email, IP, UUID, datetime, Luhn checksum, semver, ISBN, ISSN, BIC/SWIFT, cron, Data URI, BCP 47, Ethereum/Bitcoin address, PNG/JPEG/GIF/WebP/BMP/TIFF/ICO/AVIF/HEIC/SVG image magic-number validation, etc.
  • 🔗 Cross-field rules — range, fieldcontains, fieldlen, requiredWithout, etc.
  • 🌍 i18n native support — 9 built-in language translations (en/zh/zh-TW/ja/ko/fr/de/es/ru), switch with one line, extensible to any language
  • 🔄 go-playground/validator compatible — Struct tag syntax and API highly compatible, minimal migration cost
  • 🧩 JSON Schema validation — Lightweight JSON Schema subset validation, suitable for API gateway scenarios
  • 🔒 Concurrency safe — Validator instances are reusable, struct compilation results auto-cached
  • 🛠️ Custom rules — RegisterValidation for custom validation functions, context propagation supported
  • 📊 Array-style error output — TranslateValidationErrors outputs serializable JSON errors
  • 🌐 Gateway utilities — IP allowlist/blocklist (CIDR/wildcard), HTTP status codes, headers, content types, JSON Path validation
  • 📎 Format validation — email, IP, UUID, base64, URL, URI (including mailto/tel), protocol, WebSocket, semver, ISBN-10/13, ISSN, BIC/SWIFT, cron, Data URI, BCP 47 language tags, Ethereum/Bitcoin addresses, image formats (PNG/JPEG/GIF/WebP/BMP/TIFF/ICO/AVIF/HEIC/SVG via magic numbers)
  • 📦 Generic enum validator — NewEnumValidator[T] type-safe enum value validation
  • 🔀 Tag comma escaping — \, preserves commas in parameters, | as alternative separator
  • 🛑 Rule execution policy — Short-circuit on single field failure, other fields unaffected

🏗️ Architecture

graph TB
    subgraph "User Layer"
        APP["Application Code"]
    end

    subgraph "Root Package validator"
        V["Validate Instance<br/>Struct / Var / VarString"]
        CACHE["Compilation Cache<br/>structPlan"]
        TAGS["Built-in Rules<br/>87+ builtinRules"]
        STAGS["String Rules<br/>stringRuleMap"]
        TRANS["Error Translation<br/>translations.go → i18n.Lookup"]
        OPTS["Configuration<br/>Option / SetLocale"]
        ERRORS["Error Model<br/>ValidationErrors"]
    end

    subgraph "rule Package"
        RPARSE["Tag Parsing<br/>ParseTag"]
        RFIELD["Field Path<br/>FieldByPath"]
        RTIME["Time Rules<br/>TimeValue / ResolveTimeExpr"]
    end

    subgraph "validate Package"
        COMPARE["Comparison<br/>CompareNumbers / Strings"]
        FORMAT["Format Validation<br/>Email / IP / URL / UUID / Base64"]
        ENUM["Enum Validation<br/>EnumValidator"]
        JSON["JSON Validation<br/>ValidateJSON / JSONPath"]
        NETWORK["Network Validation<br/>IPSet / CIDR / Wildcard"]
        CONSTANTS["Message Constants<br/>constants.go"]
    end

    subgraph "i18n Package (Unified Translation Store)"
        I18N["i18n Core<br/>SetLocale / Msg / Lookup / Register"]
        I18N_EN["en.go"]
        I18N_ZH["zh.go / zh_tw.go"]
        I18N_JA["ja.go / ko.go"]
        I18N_OTHER["fr.go / de.go / es.go / ru.go"]
    end

    subgraph "schema Package"
        SCHEMA["JSON Schema<br/>ValidateJSONSchema"]
    end

    APP --> V
    V --> CACHE
    V --> TAGS
    V --> STAGS
    V --> TRANS
    V --> OPTS
    V --> ERRORS
    V --> RPARSE
    V --> RFIELD
    V --> RTIME

    TAGS --> FORMAT
    TAGS --> COMPARE
    TAGS --> ENUM
    STAGS --> FORMAT

    APP --> COMPARE
    APP --> FORMAT
    APP --> NETWORK
    APP --> SCHEMA

    SCHEMA --> I18N
    COMPARE --> I18N
    FORMAT --> I18N
    ENUM --> I18N
    JSON --> I18N
    NETWORK --> I18N

    OPTS --> I18N
    TRANS --> I18N

    style APP fill:#e1f5fe
    style V fill:#fff3e0
    style STAGS fill:#ffe0b2
    style I18N fill:#e8f5e9
    style SCHEMA fill:#fce4ec

📦 Installation

go get github.com/HitGameAI/apex-toolbox/pkg/argus

Requires Go 1.21+

🚀 Quick Start

package main

import (
    "fmt"
    "github.com/HitGameAI/apex-toolbox/pkg/argus"
)

type User struct {
    Name  string `json:"name" validate:"required,min=2,max=50"`
    Email string `json:"email" validate:"required,email"`
    Age   int    `json:"age" validate:"gte=0,lte=150"`
}

func main() {
    v := validator.New()
    err := v.Struct(User{Name: "A", Email: "bad", Age: -1})

    // Switch language with one line
    validator.SetLocale("en")
    messages := validator.TranslateValidationErrors(err, "en")
    for _, msg := range messages {
        fmt.Printf("%s: %s\n", msg.Field, msg.Message)
    }
    // Register new language (9 built-in: en/zh/zh-TW/ja/ko/fr/de/es/ru)
    validator.RegisterI18nMessages("pt", map[string]string{
        "required": "{field} é obrigatório",
    })
    // name: name must be at least 2 characters
    // email: email must be a valid email address
    // age: age must be greater than or equal to 0
}

🔌 Framework Integration

Argus seamlessly replaces the default validator of mainstream web frameworks. Existing binding flows like ShouldBindJSON and httpx.Parse trigger validation automatically, zero intrusion into business code:

Framework Injection Point
gin binding.Validator
Echo e.Validator
Fiber fiber.Config.StructValidator
go-zero httpx.SetValidator
chi & others manual v.Struct in handler

Complete integration examples (runnable example code, curl demos, and unified error responses): docs/frameworks.md


⚡ VarString Zero-Reflection Fast Path

For string variable validation, VarString provides a zero-allocation fast path that completely bypasses reflect:

v := validator.New()

// Traditional Var path — interface{} boxing + reflect
err := v.Var("user@example.com", "email")

// VarString zero-reflection path — direct string parameter, 0 heap allocations
err = v.VarString("user@example.com", "email")

How it works:

  • VarString looks up stringRuleMap (zero-reflection implementations of all string-compatible rules) and calls rule functions directly with string parameters
  • Unsupported rules (e.g., cross-field rules like eqfield, required_if) automatically fall back to the reflect path, maintaining full compatibility
  • Errors return lightweight stringFieldError, which also implements the FieldError interface

Supported zero-reflection rules:

required · min · max · len · eq · ne · gt · gte · lt · lte · alpha · alphanum · email · url · uri · ip · ipv4 · ipv6 · uuid · uuid3/4/5 · semver · isbn10/13 · issn · bic · cron · base64 · json · hostname · fqdn · mac · cidr · e164 · lowercase · uppercase · boolean · number · datetime · latitude · longitude · eth_addr · btc_addr · bcp47 · datauri · oneof · oneofci · contains · startswith · endswith and 70+ more rules

📚 Documentation

Document Description
docs/tags.md Complete reference for all validation tags
docs/i18n.md Internationalization guide
docs/examples.md Complete usage examples
docs/frameworks.md gin / go-zero framework integration guide

🔄 Migrating from go-playground/validator

Argus's struct tag syntax and core API are highly compatible with go-playground/validator:

// go-playground/validator
import "github.com/go-playground/validator/v10"
v := validator.New()

// Argus — just change the import path
import "github.com/HitGameAI/apex-toolbox/pkg/argus"
v := validator.New()

Key differences:

Feature go-playground/validator Argus
Third-party dependencies Multiple (e.g., utranslator) Zero
i18n Requires extra translator install 9 built-in languages
JSON Schema Not supported Built-in
IP/CIDR/Network Not supported Built-in
Zero-reflection string validation Not supported VarString 0 allocs

🚀 Performance Benchmarks

Full performance comparison between Argus and go-playground/validator/v10 is available at go-argus-benchmark.

VarString Zero-Reflection Path vs Var Reflection Path
Rule VarString (zero-reflect) Var (reflect) VarString Speedup
required 18 ns / 0 B / 0 allocs 49 ns / 16 B / 1 alloc 2.7×
email 47 ns / 0 B / 0 allocs 81 ns / 16 B / 1 alloc 1.7×
url 37 ns / 0 B / 0 allocs 64 ns / 16 B / 1 alloc 1.7×
semver 28 ns / 0 B / 0 allocs 57 ns / 16 B / 1 alloc 2.0×
isbn10 25 ns / 0 B / 0 allocs 60 ns / 16 B / 1 alloc 2.4×
cron 44 ns / 0 B / 0 allocs 74 ns / 16 B / 1 alloc 1.7×
Argus vs go-playground/validator/v10
Scenario Argus validator/v10 Advantage
Var_Email_Valid 87 ns / 0 B / 0 allocs 626 ns / 98 B / 5 allocs 🚀 7.2×
NestedWorkspace_Valid_Parallel 171 ns / 192 B / 5 allocs 768 ns / 1007 B / 33 allocs 🚀 4.5×
NestedWorkspace_Valid 1014 ns / 192 B / 5 allocs 3249 ns / 992 B / 33 allocs 🚀 3.2×
SimpleUser_Valid 341 ns / 0 B / 0 allocs 810 ns / 98 B / 5 allocs 🚀 2.4×

Key optimizations: zero-reflection VarString fast path, hand-written email parser replacing net/mail, pre-compiled rule dispatch table, sync.Pool error object reuse, zero-allocation isEmptyValue, zero-allocation lowercase/uppercase byte checks, json.NewDecoder replacing json.Valid, lightweight URL/URI parsing replacing net/url, etc. See go-argus-benchmark for details.


🔗 Ecosystem

Project Description
go-rpc-gateway Next-gen enterprise microservice gateway framework with built-in Argus as gRPC/HTTP parameter validation engine
go-toolbox/pkg/pbmo High-performance Protocol Buffer ↔ Model bidirectional conversion library with Argus field-level validation
go-toolbox/pkg/sqlbuilder Generic GORM repository layer using Argus to validate query parameters and model fields
go-toolbox Zero-dependency high-performance Go utility library with Argus validation for HTTP parameters, strings, and data structures
go-rpc-gateway Integration

go-rpc-gateway integrates Argus out of the box, providing struct tag-based gRPC interceptors. Combined with protoc-go-inject-tag to inject validate:"..." tags on generated pb code, no manual parameter validation needed:

import "github.com/HitGameAI/apex-rpc-gateway/middleware"

// gRPC Unary interceptor — auto-validates validate tags on req
unary := middleware.StructTagValidatorUnaryInterceptor()

// gRPC Stream interceptor — auto-validates each stream message
stream := middleware.StructTagValidatorStreamInterceptor()

Validation failures automatically return codes.InvalidArgument. Fields without injected tags are skipped, no false positives.


📄 License

MIT License

Documentation

Overview

Package validator 提供零依赖 struct tag 校验和服务网关常用校验能力

Index

Constants

View Source
const (
	OpEqual                    = constants.OpEqual
	OpNotEqual                 = constants.OpNotEqual
	OpGreaterThan              = constants.OpGreaterThan
	OpGreaterThanOrEqual       = constants.OpGreaterThanOrEqual
	OpLessThan                 = constants.OpLessThan
	OpLessThanOrEqual          = constants.OpLessThanOrEqual
	OpContains                 = constants.OpContains
	OpNotContains              = constants.OpNotContains
	OpHasPrefix                = constants.OpHasPrefix
	OpHasSuffix                = constants.OpHasSuffix
	OpRegex                    = constants.OpRegex
	OpEmpty                    = constants.OpEmpty
	OpNotEmpty                 = constants.OpNotEmpty
	OpSymbolEqual              = constants.OpSymbolEqual
	OpSymbolNotEqual           = constants.OpSymbolNotEqual
	OpSymbolGreaterThan        = constants.OpSymbolGreaterThan
	OpSymbolGreaterThanOrEqual = constants.OpSymbolGreaterThanOrEqual
	OpSymbolLessThan           = constants.OpSymbolLessThan
	OpSymbolLessThanOrEqual    = constants.OpSymbolLessThanOrEqual
)

Variables

This section is empty.

Functions

func CalculateIDCardChecksum

func CalculateIDCardChecksum(id string) string

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

func ClearRegexCache

func ClearRegexCache()

ClearRegexCache 清空正则缓存

func ContainsChinese

func ContainsChinese(s string) bool

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

func ContainsChineseChars

func ContainsChineseChars(s string) bool

ContainsChineseChars 检查字符串是否包含中文字符

func ContainsQuotedNumber

func ContainsQuotedNumber(data []byte) bool

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

func ConvertNumericStrings

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

ConvertNumericStrings 递归遍历 JSON 数据,将数字字符串自动转换为 json.Number 类型

func DerefValue

func DerefValue(value any) (any, bool)

DerefValue 解开 interface 中的指针值

func DetectImageFormat

func DetectImageFormat(data []byte) string

DetectImageFormat 基于魔数嗅探图片格式,返回规范格式名,无法识别时返回空字符串

func EmptyToDefault

func EmptyToDefault(str, defaultStr string) string

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

func FormatSchemaError

func FormatSchemaError(result CompareResult) string

FormatSchemaError 提取 schema 校验错误消息

func GetCompiledRegex

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

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

func GetLocale

func GetLocale() string

GetLocale 返回当前全局语言环境

func HasDoubleByte

func HasDoubleByte(s string) bool

HasDoubleByte 检查字符串是否包含双字节字符(非 ASCII)

func HasEmpty

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

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

func HasLocalIP

func HasLocalIP(ip string) bool

HasLocalIP 判断 IP 字符串是否为本地或私有地址

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 图片

func IsAllChinese

func IsAllChinese(str string) (bool, int)

IsAllChinese 检查字符串是否全部由汉字组成,返回是否全为汉字及非汉字字符数

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 IsBMP

func IsBMP(data []byte) bool

IsBMP 判断字节内容是否为有效的 BMP 图片

func IsBase64

func IsBase64(str string) bool

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

func IsBlankString

func IsBlankString(s string) bool

IsBlankString 检查字符串是否为空白(仅含空格、制表符、换行符等)

func IsCEmpty

func IsCEmpty[T comparable](v T) bool

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

func IsChineseIDCard

func IsChineseIDCard(s string) bool

IsChineseIDCard 检查字符串是否为有效的大陆身份证号(15位或18位格式)

func IsChineseIDCardWithChecksum

func IsChineseIDCardWithChecksum(s string) bool

IsChineseIDCardWithChecksum 检查18位身份证号(含校验位验证)

func IsChinesePhoneNumber

func IsChinesePhoneNumber(s string) bool

IsChinesePhoneNumber 检查字符串是否为有效的大陆手机号

func IsDecimalMN

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

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

func IsDecimalN

func IsDecimalN(s string, n int) bool

IsDecimalN 检查字符串是否为有 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 是否为文档专用地址

func IsEmail

func IsEmail(email string) bool

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

func IsEmptyAfterDeref

func IsEmptyAfterDeref(value any) (any, bool)

IsEmptyAfterDeref 解引用后判断值是否为空

func IsEmptyLine

func IsEmptyLine(s string) bool

IsEmptyLine 检查字符串是否为空白行

func IsEmptyValue

func IsEmptyValue(v reflect.Value) bool

IsEmptyValue 判断 reflect.Value 是否为空值

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 图片(含流结束符检查)

func IsGlobalUnicast

func IsGlobalUnicast(ip string) bool

IsGlobalUnicast 判断 IP 字符串是否为全球单播地址

func IsHEIC

func IsHEIC(data []byte) bool

IsHEIC 判断字节内容是否为有效的 HEIC/HEIF 图片

func IsHex

func IsHex(s string) bool

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

func IsICO

func IsICO(data []byte) bool

IsICO 判断字节内容是否为有效的 ICO 图标

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 IsImage

func IsImage(data []byte) bool

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

func IsImageInFormats

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

IsImageInFormats 判断字节内容是否为白名单内的有效图片,白名单为空格分隔的格式名,出现未知格式名时校验失败

func IsIntOrFloat

func IsIntOrFloat(s string) bool

IsIntOrFloat 检查字符串是否为整数或最多2位小数

func IsJPEG

func IsJPEG(data []byte) bool

IsJPEG 判断字节内容是否为完整的 JPEG 图片(含 EOI 尾部检查)

func IsJSONColumnType

func IsJSONColumnType(dbType string) bool

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

func IsJSONNull

func IsJSONNull(data []byte) bool

IsJSONNull 判断 JSON 字节是否为 null

func IsLengthN

func IsLengthN(s string, n int) bool

IsLengthN 检查字符串的 rune 长度是否等于 n

func IsLinkLocalIP

func IsLinkLocalIP(ip net.IP) bool

IsLinkLocalIP 判断 IP 是否为链路本地地址

func IsLowerAlpha

func IsLowerAlpha(s string) bool

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

func IsNegativeNonZeroInt

func IsNegativeNonZeroInt(s string) bool

IsNegativeNonZeroInt 检查字符串是否为负整数(首位非零)

func IsNil

func IsNil(x any) bool

IsNil 判断 interface 是否为 nil 或内部持有 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 判断字节是否是数字字符串的起始字符(数字或正负号)

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 检查字符串是否为正整数(可选+前缀,首位非零)

func IsPrivateIP

func IsPrivateIP(ip string) bool

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

func IsSVG

func IsSVG(data []byte) bool

IsSVG 判断字节内容是否为有效的 SVG 文档

func IsSafeFieldName

func IsSafeFieldName(field string) bool

IsSafeFieldName 判断字段名是否安全

func IsStrongPassword

func IsStrongPassword(s string) bool

IsStrongPassword 检查密码强度(8位+大小写+数字+特殊字符)

func IsTIFF

func IsTIFF(data []byte) bool

IsTIFF 判断字节内容是否为有效的 TIFF 图片

func IsTimeEmpty

func IsTimeEmpty(t *time.Time) bool

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

func IsTimeFormat

func IsTimeFormat(s string) bool

IsTimeFormat 校验时间格式

func IsTimeValid

func IsTimeValid(timeVal any) bool

IsTimeValid 判断时间值是否有效

func IsTrueString

func IsTrueString(s string) bool

IsTrueString 判断字符串是否表示 true(true/1/yes,大小写不敏感)

func IsUUID

func IsUUID(uuid string) bool

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

func IsUndefined

func IsUndefined(str string) bool

IsUndefined 判断字符串是否为 undefined

func IsUniqueLocalAddress

func IsUniqueLocalAddress(ip net.IP) bool

IsUniqueLocalAddress 判断 IP 是否为 IPv6 唯一本地地址(ULA)

func IsUpperAlpha

func IsUpperAlpha(s string) bool

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

func IsWebP

func IsWebP(data []byte) bool

IsWebP 判断字节内容是否为有效的 WebP 图片

func IsWordChars

func IsWordChars(s string) bool

IsWordChars 检查字符串是否由字母、数字、下划线组成

func LookupJSONPath

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

LookupJSONPath 按轻量路径读取 JSON 数据

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 NewEnumValidator

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

NewEnumValidator 创建枚举校验器

func NormalizeFilterValue

func NormalizeFilterValue(value any) any

NormalizeFilterValue 归一化过滤值

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

func ParseMonth

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

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

func ParseWeek

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

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

func RegisterI18n

func RegisterI18n(locale, key, template string)

RegisterI18n 注册或覆盖某个语言下的单个 i18n 消息模板

func RegisterI18nMessages

func RegisterI18nMessages(locale string, messages map[string]string)

RegisterI18nMessages 批量注册某个语言下的 i18n 消息模板

func RegisterTranslation

func RegisterTranslation(locale, tag, template string)

RegisterTranslation 注册或覆盖某个语言下的单个规则翻译模板

func RegisterTranslations

func RegisterTranslations(locale string, items map[string]string)

RegisterTranslations 批量注册某个语言下的规则翻译模板

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 SetLocale

func SetLocale(locale string)

SetLocale 设置全局语言环境

func SkipJSONSpaces

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

SkipJSONSpaces 跳过 JSON 字节流中的空白字符

func UnwrapProtobufEnum

func UnwrapProtobufEnum(value any) (any, bool)

UnwrapProtobufEnum 通过反射解开 protobuf enum,提取底层数值

func UnwrapProtobufWrapper

func UnwrapProtobufWrapper(value any) (any, bool)

UnwrapProtobufWrapper 通过反射解开 protobuf wrapper

func ValidateJSON

func ValidateJSON(data []byte) error

ValidateJSON 校验 JSON 字节是否有效

func ValidateJSONWithData

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

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

Types

type CompareOperator

type CompareOperator = constants.CompareOperator

CompareOperator 表示通用比较操作符

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 ValidateBase64

func ValidateBase64(str string) CompareResult

ValidateBase64 校验 Base64 字符串

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 ValidateEmail

func ValidateEmail(email string) CompareResult

ValidateEmail 校验 Email 格式

func ValidateHTTP

func ValidateHTTP(urlStr string) CompareResult

ValidateHTTP 校验 HTTP/HTTPS URL

func ValidateHeader

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

ValidateHeader 根据操作符比较 Header 值

func ValidateIP

func ValidateIP(ipStr string) CompareResult

ValidateIP 校验 IP 地址格式(兼容旧 API)

func ValidateIPAddress

func ValidateIPAddress(ipStr string) CompareResult

ValidateIPAddress 校验 IP 地址格式

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

ValidateJSONPath 校验 JSON 路径的值

func ValidateJSONPathExists

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

ValidateJSONPathExists 校验 JSON 路径是否存在

func ValidateJSONSchema

func ValidateJSONSchema(data, s any) 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, s any) CompareResult

ValidateStructWithSchema 校验结构体或 map 是否符合 schema

func ValidateUUID

func ValidateUUID(uuidStr string) CompareResult

ValidateUUID 校验 UUID 格式

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() any
	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 Func

type Func func(fl FieldLevel) bool

Func 表示自定义字段校验函数

type FuncCtx

type FuncCtx func(ctx context.Context, fl FieldLevel) bool

FuncCtx 表示带 context 的自定义字段校验函数

type IPBase

type IPBase = validate.IPBase

IPBase 提供面向对象风格的 IP 校验入口

type IPSet

type IPSet = validate.IPSet

IPSet 表示预编译 IP 规则集合

func CompileIPSet

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

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

func MustCompileIPSet

func MustCompileIPSet(patterns []string) *IPSet

MustCompileIPSet 编译 IP 规则,失败时 panic

type InvalidValidationError

type InvalidValidationError struct {
	Type reflect.Type
}

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 WithFailFast

func WithFailFast() Option

WithFailFast 首个错误即停止校验(默认关闭)

默认行为是收集全部字段错误:命中失败后仍继续遍历剩余字段, 因此"首字段失败"与"末字段失败"耗时相同(实测 15 字段结构体 482.9 vs 461.7 ns)。 请求入口的常见诉求是"拒绝这个请求",调用方往往只需首个错误或 err != nil, 此时继续校验剩余字段是纯浪费。

开启后 ValidationErrors 只含首个错误。必须显式开启而非默认—— 依赖"拿到全部错误"(如表单逐字段回显)的调用方不能被静默改掉语义。

func WithPrivateFieldValidation

func WithPrivateFieldValidation() Option

WithPrivateFieldValidation 保留私有字段校验选项,用于平滑迁移 go-playground 调用

func WithRequiredStructEnabled

func WithRequiredStructEnabled() Option

WithRequiredStructEnabled 允许 required 对非指针结构体零值生效

type SchemaBuilder

type SchemaBuilder = schema.SchemaBuilder

SchemaBuilder 提供链式构建 JSONSchema 的能力

func NewSchemaBuilder

func NewSchemaBuilder() *SchemaBuilder

NewSchemaBuilder 创建 SchemaBuilder

type TagNameFunc

type TagNameFunc func(field reflect.StructField) string

TagNameFunc 用于解析字段展示名,例如从 json tag 中取字段名

type Validate

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

Validate 是可复用且并发安全的校验器实例

func New

func New(options ...Option) *Validate

New 创建校验器实例

func (*Validate) RegisterTagNameFunc

func (v *Validate) RegisterTagNameFunc(fn TagNameFunc)

RegisterTagNameFunc 注册字段展示名解析函数

func (*Validate) RegisterValidation

func (v *Validate) RegisterValidation(tag string, fn Func, _ ...bool) error

RegisterValidation 注册自定义字段校验函数

func (*Validate) RegisterValidationCtx

func (v *Validate) RegisterValidationCtx(tag string, fn FuncCtx, _ ...bool) error

RegisterValidationCtx 注册带 context 的自定义字段校验函数

func (*Validate) SetTagName

func (v *Validate) SetTagName(name string)

SetTagName 设置校验标签名,默认使用 validate

func (*Validate) Struct

func (v *Validate) Struct(s any) error

Struct 根据结构体字段上的 validate 标签执行校验

func (*Validate) StructCtx

func (v *Validate) StructCtx(ctx context.Context, s any) error

StructCtx 根据结构体字段上的 validate 标签执行校验,并传递 context

func (*Validate) Var

func (v *Validate) Var(field any, tag string) error

Var 按标签表达式校验单个变量

func (*Validate) VarCtx

func (v *Validate) VarCtx(ctx context.Context, field any, tag string) error

VarCtx 按标签表达式校验单个变量,并传递 context

func (*Validate) VarString

func (v *Validate) VarString(field, tag string) error

VarString 按标签表达式校验字符串变量,零分配快速路径

func (*Validate) VarStringCtx

func (v *Validate) VarStringCtx(ctx context.Context, field, tag string) error

VarStringCtx 按标签表达式校验字符串变量,零反射快速路径

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           any    `json:"value,omitempty"`
	Message         string `json:"message"`
}

ValidationMessage 表示一个可直接序列化给 HTTP/gRPC 网关的字段错误

func TranslateValidationErrors

func TranslateValidationErrors(err error, locale string) []ValidationMessage

TranslateValidationErrors 将 error 转换为数组化的 i18n 字段错误

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 迁移而来的通用校验能力

Jump to

Keyboard shortcuts

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