61 lines
1.2 KiB
Go
61 lines
1.2 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
|
|
db.Select("*").Limit(5).Find(&items, "type = ?", "post")
|
|
|
|
tpl := themeManager.GetTemplate("index")
|
|
if tpl == nil {
|
|
c.String(http.StatusInternalServerError, "Template 'index' not found")
|
|
return
|
|
}
|
|
|
|
c.Header("Content-Type", "text/html; charset=utf-8")
|
|
tpl.Execute(c.Writer, gin.H{
|
|
"Items": items,
|
|
"Title": "首页",
|
|
})
|
|
}
|