增加基础设置页面
This commit is contained in:
@@ -0,0 +1,84 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
"goblog/config"
|
||||
"goblog/database"
|
||||
"goblog/models"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// 站点基础设置键名
|
||||
const (
|
||||
OptionSiteName = "site_name"
|
||||
OptionSiteDesc = "site_desc"
|
||||
OptionShowComments = "show_comments" // "1" 显示评论 / "0" 隐藏评论
|
||||
OptionCommentPageSize = "comments_per_page" // 前台评论每页条数
|
||||
)
|
||||
|
||||
// GetSettings 获取站点基础设置(管理员)
|
||||
func GetSettings(c *gin.Context) {
|
||||
cfg := config.GetGlobalConfig()
|
||||
if cfg == nil {
|
||||
cfg = config.Load()
|
||||
}
|
||||
|
||||
opts, err := models.GetOptionsByUser(database.DB, 0)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "读取设置失败"})
|
||||
return
|
||||
}
|
||||
|
||||
// 默认值:站点信息取配置文件,评论默认显示、每页 10 条
|
||||
settings := map[string]string{
|
||||
OptionSiteName: cfg.App.Name,
|
||||
OptionSiteDesc: cfg.App.Description,
|
||||
OptionShowComments: "1",
|
||||
OptionCommentPageSize: "10",
|
||||
}
|
||||
for name := range settings {
|
||||
if v, ok := opts[name]; ok && v != "" {
|
||||
settings[name] = v
|
||||
}
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{"data": settings})
|
||||
}
|
||||
|
||||
// UpdateSettingsRequest 更新站点基础设置请求
|
||||
type UpdateSettingsRequest struct {
|
||||
SiteName string `json:"site_name" binding:"required"`
|
||||
SiteDesc string `json:"site_desc"`
|
||||
ShowComments bool `json:"show_comments"`
|
||||
CommentsPerPage int `json:"comments_per_page" binding:"required,min=1,max=100"`
|
||||
}
|
||||
|
||||
// UpdateSettings 保存站点基础设置(管理员)
|
||||
func UpdateSettings(c *gin.Context) {
|
||||
var req UpdateSettingsRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "参数错误: " + err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
showComments := "0"
|
||||
if req.ShowComments {
|
||||
showComments = "1"
|
||||
}
|
||||
options := map[string]string{
|
||||
OptionSiteName: req.SiteName,
|
||||
OptionSiteDesc: req.SiteDesc,
|
||||
OptionShowComments: showComments,
|
||||
OptionCommentPageSize: strconv.Itoa(req.CommentsPerPage),
|
||||
}
|
||||
|
||||
if err := models.BatchSetOptions(database.DB, 0, options); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "保存设置失败"})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{"message": "设置已保存"})
|
||||
}
|
||||
Reference in New Issue
Block a user