package controllers import ( "go_blog/models" "go_blog/utils" "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.(*utils.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()) } }