Files
pc-monitor/server/api/handler/alert.go
672 0e8c9f7bff feat: init pc-monitor project
- Client: Go-based Windows hardware monitoring (CPU, GPU, memory, disk, network, power)
- Server: Go + Gin + SQLite backend with REST API
- Frontend: Vue 3 + Element Plus dashboard
- Docker deployment support
- Windows service installation script
2026-05-17 01:29:44 +08:00

90 lines
2.3 KiB
Go

package handler
import (
"net/http"
"pc-monitor-server/model"
"pc-monitor-server/service"
"time"
"github.com/gin-gonic/gin"
"github.com/google/uuid"
)
type AlertHandler struct {
service *service.AlertService
}
func NewAlertHandler(service *service.AlertService) *AlertHandler {
return &AlertHandler{service: service}
}
type CreateRuleRequest struct {
DeviceID string `json:"device_id" binding:"required"`
Metric string `json:"metric" binding:"required"`
Operator string `json:"operator" binding:"required"`
Threshold float64 `json:"threshold" binding:"required"`
Duration int `json:"duration"`
}
func (h *AlertHandler) CreateRule(c *gin.Context) {
var req CreateRuleRequest
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
rule := &model.AlertRule{
ID: uuid.New().String(),
DeviceID: req.DeviceID,
Metric: req.Metric,
Operator: req.Operator,
Threshold: req.Threshold,
Duration: req.Duration,
CreatedAt: time.Now(),
}
if err := h.service.CreateRule(rule); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"rule": rule})
}
func (h *AlertHandler) GetRulesByDevice(c *gin.Context) {
deviceID := c.Param("id")
rules, err := h.service.GetRulesByDevice(deviceID)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"rules": rules})
}
func (h *AlertHandler) DeleteRule(c *gin.Context) {
id := c.Param("id")
if err := h.service.DeleteRule(id); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"message": "Rule deleted"})
}
func (h *AlertHandler) GetActiveAlerts(c *gin.Context) {
alerts, err := h.service.GetActiveAlerts()
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"alerts": alerts})
}
func (h *AlertHandler) ResolveAlert(c *gin.Context) {
id := c.Param("id")
if err := h.service.ResolveAlert(id); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"message": "Alert resolved"})
}