Files
aiaa-notification-server/internal/handler/channel.go
T
ryan 39f3774940 feat: 配置列表分页与钉钉机器人分钟级排队限流
统一 sources/templates/channels/rules 列表为分页响应,避免配置增多时全量返回;按钉钉 access_token 限制每分钟发送并在超限时等待下一分钟,降低触发官方封禁风险。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-10 00:34:26 +08:00

99 lines
2.7 KiB
Go

package handler
import (
"encoding/json"
"net/http"
"strconv"
"aiaa-notification-service/internal/cache"
"aiaa-notification-service/internal/model"
"aiaa-notification-service/internal/store"
"github.com/gin-gonic/gin"
)
type ChannelHandler struct {
store *store.Store
cache *cache.Cache
}
func NewChannelHandler(s *store.Store, c *cache.Cache) *ChannelHandler {
return &ChannelHandler{store: s, cache: c}
}
type createChannelReq struct {
Name string `json:"name" binding:"required"`
Type string `json:"type" binding:"required"`
Config json.RawMessage `json:"config" binding:"required"`
Status int `json:"status"`
}
func (h *ChannelHandler) Create(c *gin.Context) {
var req createChannelReq
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
if req.Status == 0 {
req.Status = 1
}
raw := json.RawMessage(req.Config)
ch := &model.Channel{Name: req.Name, Type: req.Type, Config: &raw, Status: req.Status}
if err := h.store.CreateChannel(c.Request.Context(), ch); err != nil {
c.JSON(http.StatusConflict, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusCreated, ch)
}
func (h *ChannelHandler) List(c *gin.Context) {
var page store.PageFilter
if err := c.ShouldBindQuery(&page); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
page.Normalize()
channels, total, err := h.store.ListChannels(c.Request.Context(), page)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"data": channels, "total": total, "page": page.Page})
}
func (h *ChannelHandler) Get(c *gin.Context) {
id, _ := strconv.Atoi(c.Param("id"))
ch, err := h.store.GetChannel(c.Request.Context(), id)
if err != nil {
c.JSON(http.StatusNotFound, gin.H{"error": "channel not found"})
return
}
c.JSON(http.StatusOK, ch)
}
func (h *ChannelHandler) Update(c *gin.Context) {
id, _ := strconv.Atoi(c.Param("id"))
var req createChannelReq
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
raw := json.RawMessage(req.Config)
ch := &model.Channel{Name: req.Name, Type: req.Type, Config: &raw, Status: req.Status}
if err := h.store.UpdateChannel(c.Request.Context(), id, ch); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"ok": true})
}
func (h *ChannelHandler) Delete(c *gin.Context) {
id, _ := strconv.Atoi(c.Param("id"))
if err := h.store.DeleteChannel(c.Request.Context(), id); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"ok": true})
}