use mysql
This commit is contained in:
59
main.go
59
main.go
@@ -4,6 +4,9 @@ import (
|
||||
"go_blog/config"
|
||||
"go_blog/models"
|
||||
"go_blog/routers"
|
||||
"log/slog"
|
||||
"os"
|
||||
"time"
|
||||
|
||||
"go_blog/themes"
|
||||
|
||||
@@ -12,26 +15,52 @@ import (
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// @title 个人博客系统API
|
||||
// @version 1.0
|
||||
// @description 基于Go语言的可定制主题博客系统
|
||||
const templatePath = "./templates/*"
|
||||
|
||||
func main() {
|
||||
|
||||
//读取配置文件
|
||||
// 1. 初始化配置
|
||||
conf, err := config.LoadConfig("config.yml")
|
||||
if err != nil {
|
||||
panic("配置文件加载失败: " + err.Error())
|
||||
slog.Error("配置加载失败", "error", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
models.InitDatabase(conf)
|
||||
// 4. 初始化主题管理器
|
||||
themeManager := themes.NewManager()
|
||||
// if err := themeManager.LoadTheme(conf.GetCurrentTheme()); err != nil {
|
||||
// panic("主题加载失败: " + err.Error())
|
||||
|
||||
// 2. 初始化日志系统
|
||||
// if err := logger.Initialize(cfg.Log); err != nil {
|
||||
// slog.Error("日志初始化失败", "error", err)
|
||||
// os.Exit(1)
|
||||
// }
|
||||
// defer logger.Flush()
|
||||
logger := slog.New(slog.NewJSONHandler(os.Stdout, nil))
|
||||
slog.SetDefault(logger)
|
||||
|
||||
// 3. 初始化数据库
|
||||
models.InitDatabase(conf)
|
||||
|
||||
// 4. 初始化主题系统
|
||||
themeManager := themes.NewManager(conf.Theme.Current)
|
||||
if err := themeManager.LoadTheme(conf.Theme.Current); err != nil {
|
||||
slog.Error("主题系统初始化失败", "error", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
// 5. 创建Gin实例
|
||||
// 根据环境设置Gin模式
|
||||
if conf.Env == config.EnvProduction {
|
||||
gin.SetMode(gin.ReleaseMode)
|
||||
}
|
||||
router := gin.Default()
|
||||
router.LoadHTMLGlob(templatePath)
|
||||
themeManager.RegisterStaticRoutes(router)
|
||||
|
||||
// 6. 注册中间件
|
||||
router.Use(
|
||||
loggerMiddleware(),
|
||||
gin.Logger(),
|
||||
gin.Recovery(),
|
||||
databaseMiddleware(models.DB),
|
||||
@@ -45,7 +74,7 @@ func main() {
|
||||
// 8. 注册路由
|
||||
routers.RegisterRoutes(router)
|
||||
// 9. 启动服务
|
||||
router.Run(":" + conf.Server.Port) //router.Run()
|
||||
router.Run(":" + conf.Server.Port)
|
||||
}
|
||||
|
||||
// 自定义模板渲染器
|
||||
@@ -83,3 +112,19 @@ func themeMiddleware(manager *themes.ThemeManager) gin.HandlerFunc {
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
|
||||
func loggerMiddleware() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
start := time.Now()
|
||||
|
||||
c.Next()
|
||||
|
||||
duration := time.Since(start)
|
||||
slog.Info("请求处理完成",
|
||||
"status", c.Writer.Status(),
|
||||
"method", c.Request.Method,
|
||||
"path", c.Request.URL.Path,
|
||||
"duration", duration,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user