GoTest/cmd/main.go
2025-11-29 03:27:19 +08:00

103 lines
2.1 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/internal/handler"
"yinli-api/pkg/cache"
"yinli-api/pkg/config"
"yinli-api/pkg/database"
"github.com/gin-gonic/gin"
)
// @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)
}
// 启动服务器
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("服务器已关闭")
}