validator

package
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Aug 30, 2026 License: MIT Imports: 5 Imported by: 0

Documentation

Overview

Package validator 参数校验扩展点。 校验时机:Q/B 解析完成后、Handler 调用前(InTransform 之后)。 内置规则(绑定阶段执行):

  • query/path/header/body 字段 `binding:"required"` 或 `validate:"required"`:缺失时报错
  • Q 或 B 实现 `Validate() error` 接口:绑定后自动调用

扩展方式:

  • server.AddValidator(validator.Func) 追加自定义校验器
  • server.AddValidator(validator.Playground()) 接入 go-playground/validator(validate:"..." 完整规则), 不调用则不引入该依赖

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func IsRequired

func IsRequired(ft reflect.StructField) bool

IsRequired 判断字段是否声明必填(binding / validate 双标签兼容)

func Run

func Run(ctx context.Context, method string, q, b any, custom ...Func) error

Run 执行校验(gin/echo 适配器共用,消除两份重复实现):

  1. q/b 结构体的必填标签检查(binding:"required" / validate:"required")
  2. q/b 自带 Validate() error 方法
  3. 依次执行自定义校验器

q/b 传指针(与绑定阶段一致)。

Types

type Func

type Func func(ctx context.Context, method string, q, b any) error

Func 自定义校验器签名。method 为 HTTP 方法;q/b 为解析后的请求值(指针)。

func Playground

func Playground() Func

Playground 返回 go-playground/validator 封装校验器:支持 validate:"..." 完整规则 (required、email、min、max、oneof、自定义 tag 等。

使用:server.AddValidator(validator.Playground())

注意:调用本函数会引入 go-playground/validator 依赖(仅被 import 时才编译进二进制); 只使用内置 required + Validate() 的项目无需调用。

Jump to

Keyboard shortcuts

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