Files
go_blog/controllers/showpost.go

71 lines
2.0 KiB
Go
Raw Normal View History

2025-04-09 16:56:05 +08:00
package controllers
import (
2025-04-15 16:47:00 +08:00
"go_blog/models"
2025-05-27 19:01:05 +08:00
"go_blog/themes" // <-- 确保导入 themes 包
2025-04-09 16:56:05 +08:00
"net/http"
2025-04-15 16:47:00 +08:00
"strconv"
2025-04-09 16:56:05 +08:00
"github.com/gin-gonic/gin"
2025-05-27 19:01:05 +08:00
"gorm.io/gorm" // <-- 确保导入 gorm
2025-04-09 16:56:05 +08:00
)
func ShowPost(c *gin.Context) {
2025-05-27 19:01:05 +08:00
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
}
2025-04-15 16:47:00 +08:00
2025-05-27 19:01:05 +08:00
idParam := c.Param("id")
id, err := strconv.ParseInt(idParam, 10, 32)
2025-04-15 16:47:00 +08:00
if err != nil {
2025-05-27 19:01:05 +08:00
c.String(http.StatusBadRequest, "Invalid post ID format")
2025-04-15 16:47:00 +08:00
return
}
2025-05-27 19:01:05 +08:00
2025-04-15 16:47:00 +08:00
var content = models.Content{Cid: int32(id)}
2025-05-27 19:01:05 +08:00
// 从 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())
}
2025-04-09 16:56:05 +08:00
}