This commit is contained in:
张超
2025-05-27 19:01:05 +08:00
parent f02495cc7a
commit 5ffc64e1dd
16 changed files with 512 additions and 123 deletions

View File

@@ -2,16 +2,54 @@ package controllers
import (
"go_blog/models"
"go_blog/themes" // <-- 确保导入 themes 包
"net/http"
"github.com/gin-gonic/gin"
"gorm.io/gorm" // <-- 确保导入 gorm
)
func Home(c *gin.Context) {
tm, exists := c.Get("ThemeManager")
if !exists {
c.String(http.StatusInternalServerError, "Theme manager not found in context")
return
}
themeManager, ok := tm.(*themes.ThemeManager)
if !ok {
c.String(http.StatusInternalServerError, "Invalid theme manager type in context")
return
}
var items []models.Content
models.DB.Select("*").Limit(5).Find(&items, "type = ?", "post")
c.HTML(http.StatusOK, "index.tmpl", gin.H{
// 从 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
}
db.Select("*").Limit(5).Find(&items, "type = ?", "post")
tpl := themeManager.GetTemplate("index") // "index" 是模板的基本名 (例如 index.tmpl -> index)
if tpl == nil {
c.String(http.StatusInternalServerError, "Template 'index' not found in current theme: "+themeManager.CurrentTheme())
return
}
c.Status(http.StatusOK)
c.Header("Content-Type", "text/html; charset=utf-8")
err := tpl.Execute(c.Writer, gin.H{
"Items": items,
"Title": "首页", // 你可以根据需要传递更多数据
})
if err != nil {
// 实际项目中应记录错误
c.String(http.StatusInternalServerError, "Error rendering template: "+err.Error())
}
}

View File

@@ -2,19 +2,69 @@ 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) {
id, err := strconv.ParseInt(c.Param("id"), 10, 32)
if err != nil {
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)}
models.DB.First(&content)
c.HTML(http.StatusOK, "post.tmpl", content)
// 从 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())
}
}

39
controllers/themes.go Normal file
View File

@@ -0,0 +1,39 @@
package controllers
import (
"go_blog/themes"
"os"
"github.com/gin-gonic/gin"
)
// ListThemes 获取可用主题列表
func ListThemes(c *gin.Context) {
// 从主题管理器获取当前主题
tm, exists := c.Get("ThemeManager")
if !exists {
c.JSON(500, gin.H{"error": "主题管理器未找到"})
return
}
themeManager := tm.(*themes.ThemeManager)
// 读取 web/themes 目录下的所有主题文件夹
themesDir := "web/themes"
entries, err := os.ReadDir(themesDir)
if err != nil {
c.JSON(500, gin.H{"error": "读取主题目录失败: " + err.Error()})
return
}
var themeList []string
for _, entry := range entries {
if entry.IsDir() {
themeList = append(themeList, entry.Name())
}
}
c.JSON(200, gin.H{
"current": themeManager.CurrentTheme(),
"themes": themeList,
})
}

View File

@@ -21,7 +21,8 @@ func UsersLoginHandler(ctx *gin.Context) {
response := Response{Ctx: ctx}
var loginUser serializers.Login
if err := ctx.ShouldBind(&loginUser); err != nil {
panic(err)
response.BadRequest("请求参数错误: " + err.Error()) // 替换 panic 为错误响应
return
}
user := loginUser.GetUser()
isLoginUser := user.CheckPassword()
@@ -29,7 +30,7 @@ func UsersLoginHandler(ctx *gin.Context) {
response.BadRequest("密码错误")
return
}
token, err := jwt.GenToken(user.ID, user.Username)
token, err := jwt.GenerateToken(user)
if err != nil {
panic(err)
}
@@ -44,7 +45,8 @@ func UsersRegisterHandler(ctx *gin.Context) {
response := Response{Ctx: ctx}
var registerUser serializers.Login
if err := ctx.ShouldBind(&registerUser); err != nil {
panic(err)
response.BadRequest("请求参数错误: " + err.Error()) // 替换 panic 为错误响应
return
}
user := registerUser.GetUser()
status := user.CheckDuplicateUsername()
@@ -73,12 +75,20 @@ func UsersSetInfoHandler(ctx *gin.Context) {
response.BadRequest("获取不到参数")
return
}
currentUser := jwt.AssertUser(ctx)
if currentUser != nil {
models.DB.Model(&currentUser).Updates(jsonData)
response.Response(currentUser, nil)
// 从上下文中获取用户(假设 JWT 中间件已将用户存入 "user" 键)
user, exists := ctx.Get("user")
if !exists {
response.Unauthenticated("未登录")
return
}
currentUser, ok := user.(*models.Account) // 明确类型为 models.Account
if !ok {
response.ServerError("用户类型错误")
return
}
models.DB.Model(currentUser).Updates(jsonData)
response.Response(currentUser, nil)
}
// 修改密码
@@ -119,10 +129,14 @@ func UsersListHandler(ctx *gin.Context) {
var pager serializers.Pager
pager.InitPager(ctx)
var users []models.Account
db := models.DB.Model(&users)
total := int64(pager.Total)
db.Count(&total)
db.Offset(pager.OffSet).Limit(pager.PageSize).Find(&users)
// 先查询总记录数
var totalCount int64
models.DB.Model(&models.Account{}).Count(&totalCount)
pager.Total = int(totalCount) // 正确设置总数
// 分页查询
models.DB.Offset(pager.OffSet()).Limit(pager.PageSize).Find(&users)
pager.GetPager()
response.Response(users, pager)
}