代码推送
This commit is contained in:
82
internal/handler/config.go
Normal file
82
internal/handler/config.go
Normal file
@@ -0,0 +1,82 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"gotest/internal/model"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// ConfigHandler 系统配置处理器
|
||||
type ConfigHandler struct {
|
||||
db *gorm.DB
|
||||
}
|
||||
|
||||
// NewConfigHandler 创建系统配置处理器
|
||||
func NewConfigHandler(db *gorm.DB) *ConfigHandler {
|
||||
return &ConfigHandler{db: db}
|
||||
}
|
||||
|
||||
// GetConfig 获取配置 GET /api/v1/admin/config/:key
|
||||
func (h *ConfigHandler) GetConfig(c *gin.Context) {
|
||||
key := c.Param("key")
|
||||
var config model.Config
|
||||
if err := h.db.Where("`key` = ?", key).First(&config).Error; err != nil {
|
||||
Success(c, gin.H{"key": key, "value": "", "remark": ""})
|
||||
return
|
||||
}
|
||||
Success(c, config)
|
||||
}
|
||||
|
||||
// SetConfig 设置配置 PUT /api/v1/admin/config/:key
|
||||
func (h *ConfigHandler) SetConfig(c *gin.Context) {
|
||||
key := c.Param("key")
|
||||
var req struct {
|
||||
Value string `json:"value"`
|
||||
Remark string `json:"remark"`
|
||||
}
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
FailBadRequest(c, "参数错误")
|
||||
return
|
||||
}
|
||||
|
||||
var config model.Config
|
||||
result := h.db.Where("`key` = ?", key).First(&config)
|
||||
if result.Error == gorm.ErrRecordNotFound {
|
||||
// 创建新配置
|
||||
config = model.Config{
|
||||
Key: key,
|
||||
Value: req.Value,
|
||||
Remark: req.Remark,
|
||||
}
|
||||
if err := h.db.Create(&config).Error; err != nil {
|
||||
FailInternal(c, "创建失败: "+err.Error())
|
||||
return
|
||||
}
|
||||
} else if result.Error == nil {
|
||||
// 更新已有配置
|
||||
config.Value = req.Value
|
||||
if req.Remark != "" {
|
||||
config.Remark = req.Remark
|
||||
}
|
||||
if err := h.db.Save(&config).Error; err != nil {
|
||||
FailInternal(c, "更新失败: "+err.Error())
|
||||
return
|
||||
}
|
||||
} else {
|
||||
FailInternal(c, "数据库错误: "+result.Error.Error())
|
||||
return
|
||||
}
|
||||
|
||||
Success(c, config)
|
||||
}
|
||||
|
||||
// ListConfigs 获取所有配置 GET /api/v1/admin/config
|
||||
func (h *ConfigHandler) ListConfigs(c *gin.Context) {
|
||||
var configs []model.Config
|
||||
if err := h.db.Order("id ASC").Find(&configs).Error; err != nil {
|
||||
FailInternal(c, "查询失败: "+err.Error())
|
||||
return
|
||||
}
|
||||
Success(c, configs)
|
||||
}
|
||||
Reference in New Issue
Block a user