Files
go_blog/main.go
Zhang Chao bc59f616fd
Some checks failed
Go build / build and run (push) Has been cancelled
使用qoder优化后更新
2026-02-12 13:48:35 +08:00

119 lines
2.7 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 (
"go_blog/config"
"go_blog/models"
"go_blog/routers"
"go_blog/utils"
"log/slog"
"os"
"time"
"gorm.io/gorm"
"github.com/gin-contrib/sessions"
"github.com/gin-contrib/sessions/cookie"
"github.com/gin-gonic/gin"
)
// @title 个人博客系统
// @version 1.0
// @description 基于Go语言的可定制主题博客系统
func main() {
// 1. 初始化配置
conf, err := config.LoadConfig("config.yml")
if err != nil {
slog.Error("配置加载失败", "error", err)
os.Exit(1)
}
slog.Info("配置加载成功", "config", conf)
// 2. 初始化日志系统
logger := slog.New(slog.NewJSONHandler(os.Stdout, nil))
slog.SetDefault(logger)
slog.SetLogLoggerLevel(slog.LevelDebug)
slog.Info("初始化日志系统成功", "Defaultlogger", logger, "LogLevel", slog.LevelDebug)
// 3. 初始化数据库
models.InitDatabase(conf)
sqlDB, _ := models.DB.DB()
defer func() {
if err := sqlDB.Close(); err != nil {
slog.Error("数据库关闭异常", "error", err)
}
}()
// 4. 初始化主题系统
themeManager := utils.NewManager("web\\themes")
if err := themeManager.LoadTheme(conf.Theme.Current); err != nil {
slog.Error("主题系统初始化失败", "error", err)
os.Exit(1)
}
// 5. 创建Gin实例
if conf.Env == config.EnvProduction {
gin.SetMode(gin.ReleaseMode)
}
router := gin.New()
router.Use(gin.Recovery())
themeManager.RegisterStaticRoutes(router)
// 初始化Session存储使用Cookie
store := cookie.NewStore([]byte("your-session-secret"))
store.Options(sessions.Options{
Path: "/",
MaxAge: 86400 * 7, // 7天
HttpOnly: true,
})
// 6. 注册中间件
router.Use(
loggerMiddleware(),
databaseMiddleware(models.DB),
configMiddleware(conf),
themeMiddleware(themeManager),
sessions.Sessions("blog-session", store),
)
// 8. 注册路由
routers.RegisterRoutes(router)
// 9. 启动服务
router.Run(":" + conf.Server.Port)
}
// 数据库中间件
func databaseMiddleware(db *gorm.DB) gin.HandlerFunc {
return func(c *gin.Context) {
c.Set("DB", db)
c.Next()
}
}
// 配置上下文中间件
func configMiddleware(cfg *config.Config) gin.HandlerFunc {
return func(c *gin.Context) {
c.Set("Config", cfg)
c.Next()
}
}
// 主题管理器中间件
func themeMiddleware(manager *utils.ThemeManager) gin.HandlerFunc {
return func(c *gin.Context) {
c.Set("ThemeManager", manager)
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,
)
}
}