2025-04-09 16:56:05 +08:00
|
|
|
package controllers
|
|
|
|
|
|
|
|
|
|
import (
|
2025-04-15 16:47:00 +08:00
|
|
|
"go_blog/models"
|
2025-07-12 15:56:36 +08:00
|
|
|
"go_blog/utils"
|
2025-04-09 16:56:05 +08:00
|
|
|
"net/http"
|
|
|
|
|
|
|
|
|
|
"github.com/gin-gonic/gin"
|
2026-02-12 13:48:35 +08:00
|
|
|
"gorm.io/gorm"
|
2025-04-09 16:56:05 +08:00
|
|
|
)
|
|
|
|
|
|
2026-02-12 13:48:35 +08:00
|
|
|
// getThemeManager 从上下文中获取主题管理器
|
|
|
|
|
func getThemeManager(c *gin.Context) (*utils.ThemeManager, bool) {
|
2025-05-27 19:01:05 +08:00
|
|
|
tm, exists := c.Get("ThemeManager")
|
|
|
|
|
if !exists {
|
2026-02-12 13:48:35 +08:00
|
|
|
return nil, false
|
2025-05-27 19:01:05 +08:00
|
|
|
}
|
2025-07-12 15:56:36 +08:00
|
|
|
themeManager, ok := tm.(*utils.ThemeManager)
|
2026-02-12 13:48:35 +08:00
|
|
|
return themeManager, ok
|
|
|
|
|
}
|
2025-04-15 16:47:00 +08:00
|
|
|
|
2026-02-12 13:48:35 +08:00
|
|
|
// getDB 从上下文中获取数据库实例
|
|
|
|
|
func getDB(c *gin.Context) (*gorm.DB, bool) {
|
2025-05-27 19:01:05 +08:00
|
|
|
dbInterface, exists := c.Get("DB")
|
|
|
|
|
if !exists {
|
2026-02-12 13:48:35 +08:00
|
|
|
return nil, false
|
2025-05-27 19:01:05 +08:00
|
|
|
}
|
|
|
|
|
db, ok := dbInterface.(*gorm.DB)
|
2026-02-12 13:48:35 +08:00
|
|
|
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)
|
2025-05-27 19:01:05 +08:00
|
|
|
if !ok {
|
2026-02-12 13:48:35 +08:00
|
|
|
c.String(http.StatusInternalServerError, "DB not found")
|
2025-05-27 19:01:05 +08:00
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
|
2026-02-12 13:48:35 +08:00
|
|
|
var items []models.Content
|
2026-02-12 15:45:11 +08:00
|
|
|
result := db.Select("*").Limit(5).Find(&items, "type = ?", "post")
|
|
|
|
|
if result.Error != nil {
|
|
|
|
|
c.String(http.StatusInternalServerError, "Database error: "+result.Error.Error())
|
|
|
|
|
return
|
|
|
|
|
}
|
2025-05-27 19:01:05 +08:00
|
|
|
|
2026-02-12 13:48:35 +08:00
|
|
|
tpl := themeManager.GetTemplate("index")
|
2025-05-27 19:01:05 +08:00
|
|
|
if tpl == nil {
|
2026-02-12 13:48:35 +08:00
|
|
|
c.String(http.StatusInternalServerError, "Template 'index' not found")
|
2025-05-27 19:01:05 +08:00
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
|
2026-02-12 15:45:11 +08:00
|
|
|
data := gin.H{
|
2025-04-15 16:47:00 +08:00
|
|
|
"Items": items,
|
2026-02-12 13:48:35 +08:00
|
|
|
"Title": "首页",
|
2026-02-12 15:45:11 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
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())
|
|
|
|
|
}
|
2025-04-09 16:56:05 +08:00
|
|
|
}
|