Files
silk/server-go/internal/handler/threshold.go
T

96 lines
2.8 KiB
Go

package handler
import (
"net/http"
"silk-server-go/internal/middleware"
"silk-server-go/internal/model"
"github.com/gin-gonic/gin"
"gorm.io/gorm"
)
// RegisterThresholdRoutes 注册阈值路由
func RegisterThresholdRoutes(rg *gin.RouterGroup, db *gorm.DB) {
rg.GET("/thresholds", middleware.RequirePermission(db, "threshold:read"), listThresholds(db))
rg.GET("/thresholds/:id", middleware.RequirePermission(db, "threshold:read"), getThreshold(db))
rg.POST("/thresholds", middleware.RequirePermission(db, "threshold:write"), createThreshold(db))
rg.PATCH("/thresholds/:id", middleware.RequirePermission(db, "threshold:write"), updateThreshold(db))
rg.DELETE("/thresholds/:id", middleware.RequirePermission(db, "threshold:write"), deleteThreshold(db))
}
// listThresholds 阈值列表
func listThresholds(db *gorm.DB) gin.HandlerFunc {
return func(c *gin.Context) {
var thresholds []model.Threshold
db.Find(&thresholds)
c.JSON(http.StatusOK, thresholds)
}
}
// getThreshold 阈值详情
func getThreshold(db *gorm.DB) gin.HandlerFunc {
return func(c *gin.Context) {
id := c.Param("id")
var threshold model.Threshold
if db.Where("id = ?", id).First(&threshold).Error != nil {
c.JSON(http.StatusNotFound, gin.H{"error": "threshold not found"})
return
}
c.JSON(http.StatusOK, threshold)
}
}
// createThreshold 新建阈值
func createThreshold(db *gorm.DB) gin.HandlerFunc {
return func(c *gin.Context) {
var threshold model.Threshold
if err := c.ShouldBindJSON(&threshold); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
threshold.ID = "" // 让数据库自动生成
if err := db.Create(&threshold).Error; err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "创建失败"})
return
}
c.JSON(http.StatusCreated, threshold)
}
}
// updateThreshold 更新阈值
func updateThreshold(db *gorm.DB) gin.HandlerFunc {
return func(c *gin.Context) {
id := c.Param("id")
var threshold model.Threshold
if db.Where("id = ?", id).First(&threshold).Error != nil {
c.JSON(http.StatusNotFound, gin.H{"error": "threshold not found"})
return
}
updates, err := bindUpdates(c)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
if len(updates) > 0 {
db.Model(&model.Threshold{}).Where("id = ?", id).Updates(updates)
}
db.Where("id = ?", id).First(&threshold)
c.JSON(http.StatusOK, threshold)
}
}
// deleteThreshold 删除阈值
func deleteThreshold(db *gorm.DB) gin.HandlerFunc {
return func(c *gin.Context) {
id := c.Param("id")
var threshold model.Threshold
if db.Where("id = ?", id).First(&threshold).Error != nil {
c.JSON(http.StatusNotFound, gin.H{"error": "threshold not found"})
return
}
db.Where("id = ?", id).Delete(&model.Threshold{})
c.JSON(http.StatusOK, gin.H{"id": id})
}
}