Files
go_blog/controllers/home.go
2026-02-12 15:45:11 +08:00

69 lines
1.5 KiB
Go

package controllers
import (
"go_blog/models"
"go_blog/utils"
"net/http"
"github.com/gin-gonic/gin"
"gorm.io/gorm"
)
// getThemeManager 从上下文中获取主题管理器
func getThemeManager(c *gin.Context) (*utils.ThemeManager, bool) {
tm, exists := c.Get("ThemeManager")
if !exists {
return nil, false
}
themeManager, ok := tm.(*utils.ThemeManager)
return themeManager, ok
}
// getDB 从上下文中获取数据库实例
func getDB(c *gin.Context) (*gorm.DB, bool) {
dbInterface, exists := c.Get("DB")
if !exists {
return nil, false
}
db, ok := dbInterface.(*gorm.DB)
return db, ok
}
// Home 首页
func Home(c *gin.Context) {
themeManager, ok := getThemeManager(c)
if !ok {
c.String(http.StatusInternalServerError, "Theme manager not found")
return
}
db, ok := getDB(c)
if !ok {
c.String(http.StatusInternalServerError, "DB not found")
return
}
var items []models.Content
result := db.Select("*").Limit(5).Find(&items, "type = ?", "post")
if result.Error != nil {
c.String(http.StatusInternalServerError, "Database error: "+result.Error.Error())
return
}
tpl := themeManager.GetTemplate("index")
if tpl == nil {
c.String(http.StatusInternalServerError, "Template 'index' not found")
return
}
data := gin.H{
"Items": items,
"Title": "首页",
}
c.Header("Content-Type", "text/html; charset=utf-8")
if err := tpl.Execute(c.Writer, data); err != nil {
c.String(http.StatusInternalServerError, "Template render error: "+err.Error())
}
}