Files
backend-go/main.go

101 lines
2.7 KiB
Go

package main
// @title Trace System API
// @version 1.0
// @description 防伪溯源系统 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:8080
// @BasePath /api
// @securityDefinitions.apikey BearerAuth
// @in header
// @name Authorization
// @description Bearer token 认证
import (
"git.beifan.cn/trace-system/backend-go/config"
"git.beifan.cn/trace-system/backend-go/database"
_ "git.beifan.cn/trace-system/backend-go/docs"
"git.beifan.cn/trace-system/backend-go/logger"
"git.beifan.cn/trace-system/backend-go/routes"
"github.com/gin-contrib/cors"
"github.com/gin-gonic/gin"
swaggerFiles "github.com/swaggo/files"
ginSwagger "github.com/swaggo/gin-swagger"
)
func main() {
// 加载配置
config.LoadConfig()
cfg := config.GetAppConfig()
// 初始化日志系统
if err := logger.InitializeLogger(cfg.Server.Environment); err != nil {
panic("日志系统初始化失败: " + err.Error())
}
defer logger.Sync()
logger.Info("服务器启动",
logger.String("环境", cfg.Server.Environment),
logger.String("端口", cfg.Server.Port),
)
// 根据环境设置 Gin 模式
if cfg.Server.Environment == "production" {
gin.SetMode(gin.ReleaseMode)
} else {
gin.SetMode(gin.DebugMode)
}
// 初始化数据库
database.InitDB()
// 自动迁移数据库
database.AutoMigrate()
// 初始化 Gin 引擎
r := gin.New()
// 添加中间件
r.Use(gin.Logger())
r.Use(gin.Recovery())
// 启用 CORS
r.Use(cors.New(cors.Config{
AllowOrigins: []string{"*"},
AllowMethods: []string{"GET", "POST", "PUT", "DELETE", "OPTIONS"},
AllowHeaders: []string{"Origin", "Content-Type", "Content-Length", "Accept-Encoding", "X-CSRF-Token", "Authorization", "accept", "origin", "Cache-Control", "X-Requested-With"},
ExposeHeaders: []string{"Content-Length"},
AllowCredentials: true,
MaxAge: 12 * 3600,
}))
// 配置路由
routes.SetupRoutes(r)
// 设置 API 前缀
api := r.Group("/api")
routes.SetupAPIRoutes(api)
// Swagger 文档路由
r.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler))
// 启动服务器
port := cfg.Server.Port
logger.Info("服务器运行在 http://localhost:" + port)
logger.Info("Swagger 文档: http://localhost:" + port + "/swagger/index.html")
logger.Info("健康检查: http://localhost:" + port + "/api/health")
logger.Info("环境: " + cfg.Server.Environment)
if err := r.Run(":" + port); err != nil {
logger.Fatal("服务器启动失败", logger.Err(err))
}
}