Files
go_blog/controllers/showpost.go
2025-05-27 19:01:05 +08:00

71 lines
2.0 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 controllers
import (
"go_blog/models"
"go_blog/themes" // <-- 确保导入 themes 包
"net/http"
"strconv"
"github.com/gin-gonic/gin"
"gorm.io/gorm" // <-- 确保导入 gorm
)
func ShowPost(c *gin.Context) {
tm, exists := c.Get("ThemeManager")
if !exists {
c.String(http.StatusInternalServerError, "Theme manager not found")
return
}
themeManager, ok := tm.(*themes.ThemeManager)
if !ok {
c.String(http.StatusInternalServerError, "Invalid theme manager type")
return
}
idParam := c.Param("id")
id, err := strconv.ParseInt(idParam, 10, 32)
if err != nil {
c.String(http.StatusBadRequest, "Invalid post ID format")
return
}
var content = models.Content{Cid: int32(id)}
// 从 Gin 上下文中获取 DB 实例
dbInterface, exists := c.Get("DB")
if !exists {
c.String(http.StatusInternalServerError, "DB not found in context")
return
}
db, ok := dbInterface.(*gorm.DB)
if !ok {
c.String(http.StatusInternalServerError, "Invalid DB type in context")
return
}
result := db.First(&content)
if result.Error != nil {
if result.Error == gorm.ErrRecordNotFound {
c.String(http.StatusNotFound, "Post not found")
} else {
c.String(http.StatusInternalServerError, "Error fetching post: "+result.Error.Error())
}
return
}
// 假设你的主题中有一个名为 "post" 的模板 (post.html 或 post.tmpl)
// 注意:当前的 default 主题 (web/themes/default/templates/) 并没有 post.tmpl你需要添加它。
tpl := themeManager.GetTemplate("post")
if tpl == nil {
c.String(http.StatusInternalServerError, "Template 'post' not found in current theme: "+themeManager.CurrentTheme()+". Make sure 'post.html' or 'post.tmpl' exists in the theme's templates directory.")
return
}
c.Status(http.StatusOK)
c.Header("Content-Type", "text/html; charset=utf-8")
// 将整个 content 对象传递给模板。模板内部通过 {{ .Title }} {{ .Text }} 等访问。
err = tpl.Execute(c.Writer, content)
if err != nil {
c.String(http.StatusInternalServerError, "Error rendering template: "+err.Error())
}
}