package main import ( "exam_registration/internal/dao" "exam_registration/internal/middleware" "exam_registration/internal/routes" "exam_registration/pkg/config" "fmt" "github.com/gin-gonic/gin" "log" "net/http" "os" ) func main() { // 加载配置 if err := config.Init("config/config.yaml"); err != nil { log.Fatalf("Failed to load config: %v", err) } // 初始化数据库 if err := dao.InitMySQL(config.Config); err != nil { log.Fatalf("Failed to init database: %v", err) } // 创建 Gin 引擎 r := gin.Default() // 全局中间件 r.Use(middleware.Cors()) // 设置路由(必须在静态文件服务之前) routes.SetupRouter(r) // 静态文件服务和前端路由回退处理 distPath := "frontend/dist" if _, err := os.Stat(distPath); err == nil { // dist 目录存在,提供静态文件服务 // 使用 StaticFS 直接映射根路径到 dist 目录 r.StaticFS("/static", http.Dir(distPath+"/static")) // 显式处理根路径 - 返回 index.html r.GET("/", func(c *gin.Context) { c.File(distPath + "/index.html") }) // 前端路由回退处理(SPA 支持)- 放在最后 r.NoRoute(func(c *gin.Context) { // API 路由未找到,返回 404 if len(c.Request.URL.Path) >= 4 && c.Request.URL.Path[:4] == "/api" { c.JSON(http.StatusNotFound, gin.H{"error": "API not found"}) return } // 其他路由,返回前端 index.html(由 vue-router 处理) c.File(distPath + "/index.html") }) } else { // dist 目录不存在,提示需要构建前端 fmt.Println("⚠️ Frontend dist directory not found. Please build frontend first.") fmt.Println(" Run: cd frontend && npm install && npm run build") } // 启动服务器 port := config.Config.GetString("server.port") if err := r.Run(":" + port); err != nil { log.Fatalf("Failed to start server: %v", err) } fmt.Printf("Server started on port %s\n", port) }