gint

package module
v0.1.9 Latest Latest
Warning

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

Go to latest
Published: Mar 6, 2026 License: Apache-2.0 Imports: 10 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// CodeSuccess 成功
	CodeSuccess = 0

	// CodeWarning 警告
	// 请求处理成功,但有需要注意的信息
	CodeWarning = 1

	// CodeError 错误
	// 请求处理失败
	CodeError = 2

	// CodeInvalidParam 参数错误
	// 用于请求参数不符合接口契约(通常对应 HTTP 400)
	CodeInvalidParam = 10000

	// CodeInternalError 系统错误
	// 用于系统异常(通常对应 HTTP 500),不应将内部错误信息直接暴露给客户端
	CodeInternalError = 20000

	// CodeUnauthorized 未授权
	// 用于未登录或 Token 无效(通常对应 HTTP 401)
	CodeUnauthorized = 20001

	// CodeForbidden 禁止访问
	// 用于已登录但无权限(通常对应 HTTP 403)
	CodeForbidden = 20003
)

统一的响应码定义

Variables

View Source
var (
	// ErrNoResponse 表示不需要返回响应
	// 当你已经手动处理了响应时,可以返回这个错误
	ErrNoResponse = errors.New("不需要返回响应")

	// ErrUnauthorized 表示未授权
	// 返回这个错误会自动返回 401 状态码
	ErrUnauthorized = errors.New("未授权")

	// ErrSessionNotFound 表示 Session 不存在
	ErrSessionNotFound = errors.New("会话不存在")

	// ErrSessionExpired 表示 Session 已过期
	ErrSessionExpired = errors.New("会话已过期")

	// ErrInvalidToken 表示无效的 Token
	ErrInvalidToken = errors.New("无效的令牌")
)
View Source
var CodeMessage = map[int]string{
	CodeSuccess:       "成功",
	CodeWarning:       "警告",
	CodeError:         "错误",
	CodeInvalidParam:  "参数错误",
	CodeInternalError: "系统繁忙",
	CodeUnauthorized:  "未授权",
	CodeForbidden:     "没有权限",
}

CodeMessage 响应码对应的默认消息 注意:此 map 为只读,不要在运行时修改

Functions

func B

func B[Req any](fn func(ctx *gctx.Context, req Req) (Result, error)) gin.HandlerFunc

B (Bind) 带参数绑定的包装器 使用泛型自动绑定请求参数,适用于需要接收请求参数的接口

示例:

type LoginReq struct {
   Username string `json:"username"`
   Password string `json:"password"`
}

router.POST("/login", gint.B(func(ctx *gint.Context, req LoginReq) (gint.Result, error) {
   // req 已经自动绑定
   return gint.Result{Code: 0, Data: "登录成功"}, nil
}))

func BS

func BS[Req any](fn func(ctx *gctx.Context, req Req, sess session.Session) (Result, error)) gin.HandlerFunc

BS (Bind + Session) 带参数绑定和 Session 的包装器 结合了 B 和 S 的功能,适用于需要登录且需要接收参数的接口

示例:

type UpdateProfileReq struct {
   Nickname string `json:"nickname"`
   Avatar   string `json:"avatar"`
}

router.POST("/profile", gint.BS(func(ctx *gint.Context, req UpdateProfileReq, sess session.Session) (gint.Result, error) {
   userId := sess.Claims().UserId
   // 更新用户信息...
   return gint.Result{Code: 0, Msg: "更新成功"}, nil
}))

func GetCodeMessage

func GetCodeMessage(code int) string

GetCodeMessage 获取响应码对应的默认消息

func IsPassword

func IsPassword(password string) bool

IsPassword 检查是否为有效密码(包含字母和数字)

func IsStrongPassword

func IsStrongPassword(password string) bool

IsStrongPassword 检查是否为强密码(包含大小写字母、数字和特殊字符)

func S

func S(fn func(ctx *gctx.Context, sess session.Session) (Result, error)) gin.HandlerFunc

S (Session) 带 Session 的包装器 自动获取和校验 Session,适用于需要登录态的接口

示例:

router.GET("/profile", gint.S(func(ctx *gint.Context, sess session.Session) (gint.Result, error) {
   userId := sess.Claims().UserId
   return gint.Result{Code: 0, Data: userId}, nil
}))

func W

func W(fn func(ctx *gctx.Context) (Result, error)) gin.HandlerFunc

W (Wrapper) 基础包装器 只接收 Context,适用于不需要参数绑定和 Session 的简单接口

示例:

router.GET("/ping", gint.W(func(ctx *gint.Context) (gint.Result, error) {
   return gint.Result{Code: 0, Msg: "pong"}, nil
}))

Types

type CompositeRule

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

CompositeRule 组合规则

func (*CompositeRule) Validate

func (r *CompositeRule) Validate(value any) error

type Context

type Context = gctx.Context

type CustomRule

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

CustomRule 自定义规则

func (*CustomRule) Validate

func (r *CustomRule) Validate(value any) error

type EmailRule

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

EmailRule 邮箱规则

func (*EmailRule) Validate

func (r *EmailRule) Validate(value any) error

type EqualsRule

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

EqualsRule 相等规则

func (*EqualsRule) Validate

func (r *EqualsRule) Validate(value any) error

type FieldValidator

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

FieldValidator 字段校验器(建造者模式)

func NewFieldValidator

func NewFieldValidator(fieldName string, value any) *FieldValidator

NewFieldValidator 创建字段校验器

func (*FieldValidator) AddRule

func (fv *FieldValidator) AddRule(rule ValidationRule) *FieldValidator

AddRule 添加校验规则

func (*FieldValidator) Validate

func (fv *FieldValidator) Validate() []string

Validate 执行校验

type Handler

type Handler interface {
	// PrivateRoutes 注册需要认证的路由
	PrivateRoutes(server *gin.Engine)
	// PublicRoutes 注册公开的路由
	PublicRoutes(server *gin.Engine)
}

Handler 定义了路由处理器接口 用于组织和注册路由

type InRule

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

InRule 枚举规则

func (*InRule) Validate

func (r *InRule) Validate(value any) error

type LengthRangeRule

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

LengthRangeRule 长度范围规则

func (*LengthRangeRule) Validate

func (r *LengthRangeRule) Validate(value any) error

type MaxLengthRule

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

MaxLengthRule 最大长度规则

func (*MaxLengthRule) Validate

func (r *MaxLengthRule) Validate(value any) error

type MinLengthRule

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

MinLengthRule 最小长度规则

func (*MinLengthRule) Validate

func (r *MinLengthRule) Validate(value any) error

type MobileRule

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

MobileRule 手机号规则

func (*MobileRule) Validate

func (r *MobileRule) Validate(value any) error

type PageData

type PageData[T any] struct {
	List  []T   `json:"list"`  // 数据列表
	Total int64 `json:"total"` // 总数
	Page  int   `json:"page"`  // 当前页码
	Size  int   `json:"size"`  // 每页大小
}

PageData 用于返回分页查询的数据

type PageRequest

type PageRequest struct {
	Page int `json:"page" form:"page"` // 页码,从 1 开始
	Size int `json:"size" form:"size"` // 每页大小
}

PageRequest 通用的分页请求参数

func (*PageRequest) Offset

func (p *PageRequest) Offset() int

Offset 计算偏移量

func (*PageRequest) Validate

func (p *PageRequest) Validate()

Validate 验证分页参数

type PatternRule

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

PatternRule 正则规则

func (*PatternRule) Validate

func (r *PatternRule) Validate(value any) error

type RangeRule

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

RangeRule 数值范围规则

func (*RangeRule) Validate

func (r *RangeRule) Validate(value any) error

type RequiredRule

type RequiredRule struct{}

RequiredRule 必填规则

func (*RequiredRule) Validate

func (r *RequiredRule) Validate(value any) error

type Result

type Result struct {
	Code int    `json:"code"` // 业务状态码,0 表示成功
	Msg  string `json:"msg"`  // 响应消息
	Data any    `json:"data"` // 响应数据
}

Result 统一的响应结构

func Error

func Error(msg string) Result

Error 创建错误响应

func ErrorWithCode

func ErrorWithCode(code int, msg string) Result

ErrorWithCode 创建带自定义错误码的响应

func Forbidden

func Forbidden() Result

Forbidden 创建禁止访问响应

func InternalError

func InternalError() Result

InternalError 创建系统错误响应 注意:该响应用于对外返回统一文案,内部错误细节应记录在日志中

func InvalidParam

func InvalidParam(msg string) Result

InvalidParam 创建参数错误响应

func Success

func Success(msg string, data any) Result

Success 创建成功响应

func Unauthorized

func Unauthorized() Result

Unauthorized 创建未授权响应

func Warning

func Warning(msg string, data any) Result

Warning 创建警告响应

type URLRule

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

URLRule URL 规则

func (*URLRule) Validate

func (r *URLRule) Validate(value any) error

type ValidationRule

type ValidationRule interface {
	Validate(value any) error
}

ValidationRule 校验规则接口(策略模式)

func And

func And(rules ...ValidationRule) ValidationRule

And 组合多个规则(所有规则都必须通过)

func ChineseName

func ChineseName() ValidationRule

ChineseName 中文姓名规则(2-4个汉字)

func Custom

func Custom(validateFunc func(value any) error) ValidationRule

Custom 自定义规则构造函数

func CustomCondition

func CustomCondition(condition bool, errMsg string) ValidationRule

CustomCondition 自定义条件规则构造函数

func Email

func Email() ValidationRule

Email 邮箱规则构造函数

func Equals

func Equals(compareValue any) ValidationRule

Equals 相等规则构造函数

func IDCard

func IDCard() ValidationRule

IDCard 身份证号规则

func In

func In(options ...string) ValidationRule

In 枚举规则构造函数

func LengthRange

func LengthRange(min, max int) ValidationRule

LengthRange 长度范围规则构造函数

func MaxLength

func MaxLength(max int) ValidationRule

MaxLength 最大长度规则构造函数

func MinLength

func MinLength(min int) ValidationRule

MinLength 最小长度规则构造函数

func Mobile

func Mobile() ValidationRule

Mobile 手机号规则构造函数

func Password

func Password() ValidationRule

Password 密码规则(至少包含字母和数字,6-20位)

func Pattern

func Pattern(pattern string, errMsg ...string) ValidationRule

Pattern 正则规则构造函数

func Range

func Range(min, max int) ValidationRule

Range 数值范围规则构造函数

func Required

func Required() ValidationRule

Required 必填规则构造函数

func StrongPassword

func StrongPassword() ValidationRule

StrongPassword 强密码规则(大小写字母、数字、特殊字符,8-20位)

func URL

func URL() ValidationRule

URL URL 规则构造函数

func Username

func Username() ValidationRule

Username 用户名规则(字母、数字、下划线,4-20位)

type ValidatorBuilder

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

ValidatorBuilder 校验器构建器(建造者模式)

func NewValidatorBuilder

func NewValidatorBuilder() *ValidatorBuilder

NewValidatorBuilder 创建校验器构建器

func (*ValidatorBuilder) Field

func (vb *ValidatorBuilder) Field(fieldName string, value any) *FieldValidator

Field 添加字段校验

func (*ValidatorBuilder) GetErrorString

func (vb *ValidatorBuilder) GetErrorString() string

GetErrorString 获取错误字符串

func (*ValidatorBuilder) GetErrors

func (vb *ValidatorBuilder) GetErrors() []string

GetErrors 获取所有错误

func (*ValidatorBuilder) GetFirstError

func (vb *ValidatorBuilder) GetFirstError() string

GetFirstError 获取第一个错误

func (*ValidatorBuilder) IsValid

func (vb *ValidatorBuilder) IsValid() bool

IsValid 检查是否通过校验

func (*ValidatorBuilder) Validate

func (vb *ValidatorBuilder) Validate() *ValidatorBuilder

Validate 执行所有校验

Directories

Path Synopsis
middlewares

Jump to

Keyboard shortcuts

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