🚀 ThinkGin 2.0 框架文档
ThinkGin 2.0 是一个基于 Gin 框架的现代化 Go 语言 Web 应用框架,专注于提供高性能、模块化、可观测性的企业级解决方案。
版本信息:当前文档对应 ThinkGin v2.0.1,要求 Go 1.18 或更高版本。
⚡ 快速开始
环境要求
组件 | 最低版本 | 推荐版本 | 说明 |
---|---|---|---|
Go | 1.18 | 1.20+ | 支持泛型和新特性 |
内存 | 512MB | 1GB+ | 运行时内存需求 |
磁盘 | 100MB | 500MB+ | 包含日志和缓存 |
安装步骤
# 1. 克隆项目 git clone https://github.com/your-repo/thinkgin.git cd thinkgin # 2. 安装依赖 go mod tidy # 3. 运行项目 go run main.go # 4. 访问应用 curl http://localhost:8000/
启动成功!如果看到服务器启动信息,说明安装成功。访问 http://localhost:8000 查看效果。
🏗️ 架构设计
项目结构
thinkgin/ ├── 📁 app/ # 应用层 │ ├── 📁 index/ # 业务模块 │ │ ├── 📁 controller/ # 控制器 │ │ ├── 📁 model/ # 数据模型 │ │ └── 📁 view/ # 视图模板 │ └── 📄 config.go # 配置管理 ├── 📁 config/ # 配置文件 │ ├── 📄 app.yaml # 应用配置 │ ├── 📄 server.yaml # 服务器配置 │ └── 📄 database.yaml # 数据库配置 ├── 📁 route/ # 路由定义 ├── 📁 extend/ # 扩展组件 ├── 📁 public/ # 静态资源 └── 📄 main.go # 程序入口
MVC 架构模式
ThinkGin 采用经典的 MVC(Model-View-Controller)架构模式,确保代码结构清晰、职责分离:
Controller (控制器)
处理HTTP请求,调用业务逻辑,返回响应数据
Model (模型)
定义数据结构,处理数据库操作,封装业务逻辑
View (视图)
展示层,包含HTML模板、静态资源等前端内容
✨ 核心特性
高性能
基于 Gin 框架,提供极致的HTTP性能,支持高并发场景
模块化配置
YAML驱动的配置管理,支持环境切换和热重载
完整监控
内置 Prometheus 指标收集和 Grafana 可视化
结构化日志
基于 Logrus 的日志系统,支持多级别和格式化输出
链路追踪
支持 Jaeger、Zipkin 分布式链路追踪
安全防护
JWT认证、CORS跨域、安全中间件一应俱全
⚙️ 配置管理
配置文件结构
ThinkGin 使用 YAML 格式的配置文件,支持模块化配置管理:
# config/app.yaml app: name: "ThinkGin" version: "2.0.1" debug: true timezone: "Asia/Shanghai" # config/server.yaml server: mode: "debug" http: host: "0.0.0.0" port: 8000 read_timeout: 60 write_timeout: 60
注意:生产环境请将 debug 模式设置为 false,并配置合适的日志级别。
🛣️ 路由系统
基础路由
// route/router.go func InitRouter() *gin.Engine { r := gin.Default() // 基础路由 r.GET("/", controller.Index) r.GET("/hello", controller.Hello) // 路由组 api := r.Group("/api/v1") { api.GET("/users", controller.GetUsers) api.POST("/users", controller.CreateUser) api.PUT("/users/:id", controller.UpdateUser) api.DELETE("/users/:id", controller.DeleteUser) } return r }
路由参数
// 路径参数 r.GET("/user/:id", func(c *gin.Context) { id := c.Param("id") c.JSON(200, gin.H{"user_id": id}) }) // 查询参数 r.GET("/search", func(c *gin.Context) { keyword := c.Query("q") page := c.DefaultQuery("page", "1") c.JSON(200, gin.H{"keyword": keyword, "page": page}) })
🔗 中间件系统
内置中间件
JWT 认证
基于 JWT 的用户认证和授权
CORS 跨域
配置跨域资源共享策略
请求日志
记录请求响应时间和状态
限流中间件
API 访问频率限制
自定义中间件
// extend/middleware/auth.go func JWTAuth() gin.HandlerFunc { return func(c *gin.Context) { token := c.GetHeader("Authorization") if token == "" { c.JSON(401, gin.H{"error": "未授权访问"}) c.Abort() return } // 验证 JWT token if !validateToken(token) { c.JSON(401, gin.H{"error": "token 无效"}) c.Abort() return } c.Next() } }
💾 数据库集成
支持的数据库
数据库 | 驱动 | 状态 | 说明 |
---|---|---|---|
MySQL | GORM | ✅ 支持 | 主要关系型数据库 |
PostgreSQL | GORM | ✅ 支持 | 高级关系型数据库 |
Redis | go-redis | ✅ 支持 | 缓存和会话存储 |
MongoDB | mongo-driver | 🚧 开发中 | 文档型数据库 |
数据库配置
# config/database.yaml database: mysql: host: "localhost" port: 3306 username: "root" password: "password" database: "thinkgin" charset: "utf8mb4" max_open_conns: 100 max_idle_conns: 10 redis: host: "localhost" port: 6379 password: "" db: 0 pool_size: 10
💡 示例代码
创建 API 接口
// app/user/controller/user.go package controller import ( "net/http" "github.com/gin-gonic/gin" ) type User struct { ID int `json:"id"` Name string `json:"name"` Email string `json:"email"` } func GetUsers(c *gin.Context) { users := []User{ {ID: 1, Name: "张三", Email: "[email protected]"}, {ID: 2, Name: "李四", Email: "[email protected]"}, } c.JSON(http.StatusOK, gin.H{ "code": 200, "message": "success", "data": users, }) } func CreateUser(c *gin.Context) { var user User if err := c.ShouldBindJSON(&user); err != nil { c.JSON(http.StatusBadRequest, gin.H{ "code": 400, "message": err.Error(), }) return } // 保存到数据库 // db.Create(&user) c.JSON(http.StatusCreated, gin.H{ "code": 201, "message": "用户创建成功", "data": user, }) }
使用中间件
// 在路由中使用中间件 api := r.Group("/api/v1") api.Use(middleware.JWTAuth()) // 使用 JWT 认证 api.Use(middleware.CORS()) // 使用 CORS 中间件 { api.GET("/protected", controller.ProtectedHandler) api.POST("/upload", controller.UploadHandler) }
❓ 常见问题
性能优化
Q: 如何提高应用性能?
A: 1) 使用连接池 2) 启用 Gzip 压缩 3) 合理使用缓存 4) 优化数据库查询 5) 使用 CDN 加速静态资源
A: 1) 使用连接池 2) 启用 Gzip 压缩 3) 合理使用缓存 4) 优化数据库查询 5) 使用 CDN 加速静态资源
部署相关
Q: 如何部署到生产环境?
A: 推荐使用 Docker 容器化部署,配合 Nginx 做反向代理,使用 PM2 或 Supervisor 进行进程管理。
A: 推荐使用 Docker 容器化部署,配合 Nginx 做反向代理,使用 PM2 或 Supervisor 进行进程管理。
安全建议
安全提示:
- 生产环境请使用 HTTPS
- 定期更新依赖包
- 配置合适的 CORS 策略
- 使用强密码和密钥
- 启用访问日志监控