This repository has been archived on 2026-04-05. You can view files and clone it. You cannot open issues or pull requests or push a commit.
Files
Exam_registration/cmd/main.go
T

65 lines
1.6 KiB
Go

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())
// 静态文件服务和前端路由回退处理
distPath := "frontend/dist"
if _, err := os.Stat(distPath); err == nil {
// dist 目录存在,提供静态文件服务
r.Static("/static", distPath)
// 前端路由回退处理(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")
}
// 设置路由
routes.SetupRouter(r)
// 启动服务器
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)
}