gint

package module
v0.0.1 Latest Latest
Warning

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

Go to latest
Published: Dec 8, 2025 License: Apache-2.0 Imports: 10 Imported by: 0

README

# gint

License Go Report Card

基于 Gin 框架的轻量级增强库,专注于核心功能,简单易用。

💡 定位说明:gint 是 ginx 的轻量级衍生项目,只保留最常用的核心功能,适合中小型项目和快速开发。如果需要完整的企业级功能,请使用原项目 ginx。

📜 版权声明:本项目基于 ginx 开发,遵循 Apache License 2.0。感谢 ginx 原作者及贡献者的优秀工作。详见 NOTICE 文件。

✨ 特性

  • 🚀 优雅的 Handler 包装器 - W/B/S/BS 四种包装函数,简化业务逻辑编写
  • 🔐 双 Token 认证 - Access Token + Refresh Token,支持无感刷新
  • 🔄 完善的 Session 管理 - JWT + Redis 混合方案,Token 包含 UserId
  • 🛡️ 统一的错误处理 - 内置错误处理机制,代码更简洁
  • 📝 实用的中间件 - 访问日志、限流、活跃连接限制、CORS
  • 🔒 Casbin 权限管理 - 基于 RBAC 的权限管理,接口抽象设计
  • 🎯 类型安全 - 使用泛型提供类型安全的参数绑定
  • 💡 中文注释 - 完整的中文注释,易于理解

📦 安装

go get github.com/ink-yht-code/gint

🚀 快速开始

package main

import (
    "github.com/gin-gonic/gin"
    "github.com/ink-yht-code/gint"
    "github.com/ink-yht-code/gint/gctx"
)

func main() {
    r := gin.Default()
    
    // 简单接口
    r.GET("/ping", gint.W(func(ctx *gctx.Context) (gint.Result, error) {
        return gint.Result{Code: 0, Msg: "pong"}, nil
    }))
    
    // 带参数绑定
    type LoginReq struct {
        Username string `json:"username" binding:"required"`
        Password string `json:"password" binding:"required"`
    }
    
    r.POST("/login", gint.B(func(ctx *gctx.Context, req LoginReq) (gint.Result, error) {
        // 参数已自动绑定和验证
        return gint.Result{Code: 0, Msg: "登录成功"}, nil
    }))
    
    r.Run(":8080")
}

📚 文档

💡 核心概念

Handler 包装器

gint 提供四种包装器,自动处理参数绑定、Session 验证、错误处理等:

  • W - 基础包装器,只接收 Context
  • B - 带参数绑定的包装器
  • S - 带 Session 的包装器
  • BS - 参数绑定 + Session 的包装器

Session 管理

JWT + Redis 混合存储方案:

  • JWT - 存储轻量数据(用户ID、角色等)
  • Redis - 存储完整会话数据
  • 自动续期 - 访问时自动刷新过期时间

中间件

  • 访问日志 - 记录请求和响应信息
  • 限流器 - 支持 IP 限流和用户限流
  • 活跃连接限制 - 限制同时处理的请求数
  • CORS - 处理跨域请求

🔄 与 ginx 的对比

特性 ginx gint
定位 企业级框架 轻量级核心库
UserID 类型 int64 string
注释语言 英文 中文
核心功能
活跃连接限制
Memory Session
CORS
爬虫检测 ❌ (暂未实现)
依赖 ekit 仅 Gin 生态

如何选择?

  • ginx - 大型企业项目,需要完整功能
  • gint - 中小型项目,快速开发,简单易用

详细对比请查看 项目概览

🙏 致谢

本项目基于 ginx 开发,感谢原作者 ecodeclub 及所有贡献者的优秀工作。

gint 在 ginx 的基础上进行了以下改进:

  • 简化架构,专注核心功能
  • 重新设计 Session 管理,实现双 Token 机制
  • 采用设计模式重构参数校验系统
  • 添加统一的响应码规范
  • 完整的中文文档

📄 开源协议

本项目采用 Apache License 2.0 开源协议。

版权归属

  • gint: Copyright 2025 Light-ink-yht
  • ginx (原始项目): Copyright by ecodeclub and contributors

合规声明

本项目严格遵守 Apache License 2.0 的所有条款:

✅ 保留了原始项目的版权声明和归属信息
✅ 在 NOTICE 文件中详细说明了衍生关系
✅ 标记了所有修改的文件
✅ 使用相同的 Apache License 2.0 协议
✅ 提供了完整的修改说明文档

第三方依赖

本项目使用的第三方库及其协议:

完整的归属信息请查看 NOTICE 文件。


免责声明:本项目按"原样"提供,不提供任何明示或暗示的保证。详见 LICENSE 文件。

Documentation

Index

Constants

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

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

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

统一的响应码定义

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:   "错误",
}

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 Success

func Success(msg string, data any) Result

Success 创建成功响应

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
gint module
gint-gen module
gintx module
internal
jwt
middlewares

Jump to

Keyboard shortcuts

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