Files

58 lines
1.6 KiB
Go
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package api
import (
"errors"
"net/http"
"github.com/gin-gonic/gin"
"ws_usernode/internal/service"
)
// SettingsHandler 系统设置接口(adminPLAN F7)。
type SettingsHandler struct {
svc *service.SettingService
}
// NewSettingsHandler 创建设置 handler。
func NewSettingsHandler(svc *service.SettingService) *SettingsHandler {
return &SettingsHandler{svc: svc}
}
// List GET /settings —— 全部设置项(config 默认值 + settings 覆盖)。
func (h *SettingsHandler) List(c *gin.Context) {
items, err := h.svc.GetAll(c.Request.Context())
if err != nil {
fail(c, http.StatusInternalServerError, err.Error())
return
}
ok(c, gin.H{"items": items})
}
// SettingUpdateRequest 更新单个设置项。
type SettingUpdateRequest struct {
Key string `json:"key" binding:"required"`
Value string `json:"value" binding:"required"`
}
// Update PUT /settings —— 更新设置项(仅白名单 key,值为时长格式)。
func (h *SettingsHandler) Update(c *gin.Context) {
var req SettingUpdateRequest
if err := c.ShouldBindJSON(&req); err != nil {
fail(c, http.StatusBadRequest, "请求参数不合法: "+err.Error())
return
}
if err := h.svc.Set(c.Request.Context(), req.Key, req.Value); err != nil {
switch {
case errors.Is(err, service.ErrSettingKeyUnknown):
fail(c, http.StatusBadRequest, err.Error())
case errors.Is(err, service.ErrSettingValueInvalid):
fail(c, http.StatusBadRequest, err.Error())
default:
fail(c, http.StatusInternalServerError, err.Error())
}
return
}
ok(c, gin.H{"status": "updated", "key": req.Key, "value": req.Value})
}