GoTest/src/main.go
Table 84055fecfe feat: 优化 API 文档生成和 Swagger UI 服务
- 优化 make docs 命令:
  * 自动检查并安装 swag 工具
  * 自动过滤 swag 生成过程中的警告信息
  * 自动修复生成的 docs.go 文件中的兼容性问题(移除 LeftDelim 和 RightDelim 字段)

- 优化 make docs-serve 命令:
  * 使用 Docker 运行 Swagger UI 容器,提供完整的 Swagger UI 界面
  * 新增 make docs-stop 命令,用于停止 Swagger UI 容器
  * 引入 SWAGGER_PORT 变量统一管理 Swagger UI 端口配置(默认 8081)

- 修复应用内置 Swagger UI 无法加载文档问题:
  * 在 main.go 中导入生成的 docs 包(_ "yinli-api/doc/dev")
  * 修复 docs.go 文件中的兼容性问题
  * 解决 "Failed to load API definition" 错误

- 更新 CHANGELOG.md,记录所有变更
2025-11-29 20:07:24 +08:00

109 lines
2.4 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package main
import (
"flag"
"log"
"os"
"os/signal"
"syscall"
"yinli-api/src/handler"
"yinli-api/src/pkg/cache"
"yinli-api/src/pkg/config"
"yinli-api/src/pkg/database"
"github.com/gin-gonic/gin"
// 导入 Swagger 文档(根据环境动态导入)
_ "yinli-api/doc/dev" // 默认使用 dev 环境的文档
)
// @title Yinli API
// @version 1.0
// @description 这是一个基于Gin框架的API服务
// @termsOfService http://swagger.io/terms/
// @contact.name API Support
// @contact.url http://www.swagger.io/support
// @contact.email support@swagger.io
// @license.name Apache 2.0
// @license.url http://www.apache.org/licenses/LICENSE-2.0.html
// @host localhost:1234
// @BasePath /api
// @securityDefinitions.apikey ApiKeyAuth
// @in header
// @name Authorization
// @description Type "Bearer" followed by a space and JWT token.
func main() {
// 解析命令行参数
var env string
flag.StringVar(&env, "env", "dev", "运行环境 (dev, stage, prod)")
flag.Parse()
// 从环境变量获取环境配置
if envVar := os.Getenv("APP_ENV"); envVar != "" {
env = envVar
}
// 加载配置
cfg, err := config.LoadConfig(env)
if err != nil {
log.Fatalf("加载配置失败: %v", err)
}
// 设置Gin模式
gin.SetMode(cfg.Server.Mode)
// 初始化数据库
if err := database.InitDatabase(cfg); err != nil {
log.Fatalf("初始化数据库失败: %v", err)
}
defer database.CloseDatabase()
// 初始化Redis
if err := cache.InitRedis(cfg); err != nil {
log.Fatalf("初始化Redis失败: %v", err)
}
defer cache.CloseRedis()
// 创建Gin引擎
r := gin.New()
// 设置路由
handler.SetupRoutes(r)
// 如果是开发环境,添加测试路由
if cfg.Server.Mode == "debug" {
handler.SetupTestRoutes(r)
}
// 启动服务器
if cfg.Server.Port == "" {
log.Fatalf("❌ 错误: 服务器端口配置为空!请检查配置文件中的 server.port 设置")
}
log.Printf("服务器启动在端口 %s环境: %s", cfg.Server.Port, env)
// 优雅关闭
go func() {
if err := r.Run(":" + cfg.Server.Port); err != nil {
log.Fatalf("服务器启动失败: %v", err)
}
}()
// 等待中断信号
quit := make(chan os.Signal, 1)
signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
<-quit
log.Println("正在关闭服务器...")
// 这里可以添加优雅关闭的逻辑
// 比如关闭数据库连接、Redis连接等
log.Println("服务器已关闭")
}