73 lines
2.4 KiB
Go
73 lines
2.4 KiB
Go
package rule
|
|
|
|
import (
|
|
"encoding/json"
|
|
"net/http"
|
|
|
|
"git.ilapage.cn/ila/yovision/Bell/server/app/audit"
|
|
"git.ilapage.cn/ila/yovision/Bell/server/app/auth"
|
|
"git.ilapage.cn/ila/yovision/Bell/server/app/rbac"
|
|
)
|
|
|
|
type HTTP struct {
|
|
Service Service
|
|
Auth auth.HTTP
|
|
Audit audit.Store
|
|
}
|
|
|
|
func (h HTTP) Register(mux *http.ServeMux) {
|
|
mux.Handle("GET /api/v1/rules", h.Auth.Require(rbac.RulesRead, http.HandlerFunc(h.list)))
|
|
mux.Handle("POST /api/v1/rules", h.Auth.Require(rbac.RulesWrite, http.HandlerFunc(h.create)))
|
|
mux.Handle("PUT /api/v1/rules/{id}/enabled", h.Auth.Require(rbac.RulesWrite, http.HandlerFunc(h.setEnabled)))
|
|
}
|
|
func (h HTTP) list(w http.ResponseWriter, r *http.Request) {
|
|
items, err := h.Service.List(r.Context())
|
|
if err != nil {
|
|
writeJSON(w, 500, map[string]string{"error": "读取规则失败"})
|
|
return
|
|
}
|
|
writeJSON(w, 200, map[string]any{"items": items})
|
|
}
|
|
func (h HTTP) create(w http.ResponseWriter, r *http.Request) {
|
|
var input CreateInput
|
|
if err := decode(w, r, &input); err != nil {
|
|
writeJSON(w, 400, map[string]string{"error": "请求格式无效"})
|
|
return
|
|
}
|
|
item, err := h.Service.Create(r.Context(), input)
|
|
if err != nil {
|
|
writeJSON(w, 400, map[string]string{"error": err.Error()})
|
|
return
|
|
}
|
|
actor := auth.Principal(r.Context())
|
|
_ = h.Audit.Record(r.Context(), &actor.ID, "rule.created", "rule", &item.ID, "success", map[string]any{"version": item.Version})
|
|
writeJSON(w, 201, item)
|
|
}
|
|
func (h HTTP) setEnabled(w http.ResponseWriter, r *http.Request) {
|
|
var input struct {
|
|
Enabled bool `json:"enabled"`
|
|
}
|
|
if err := decode(w, r, &input); err != nil {
|
|
writeJSON(w, 400, map[string]string{"error": "请求格式无效"})
|
|
return
|
|
}
|
|
item, err := h.Service.SetEnabled(r.Context(), r.PathValue("id"), input.Enabled)
|
|
if err != nil {
|
|
writeJSON(w, 404, map[string]string{"error": "规则不存在"})
|
|
return
|
|
}
|
|
actor := auth.Principal(r.Context())
|
|
_ = h.Audit.Record(r.Context(), &actor.ID, "rule.enabled_changed", "rule", &item.ID, "success", map[string]any{"enabled": item.Enabled, "version": item.Version})
|
|
writeJSON(w, 200, item)
|
|
}
|
|
func decode(w http.ResponseWriter, r *http.Request, value any) error {
|
|
decoder := json.NewDecoder(http.MaxBytesReader(w, r.Body, 1<<20))
|
|
decoder.DisallowUnknownFields()
|
|
return decoder.Decode(value)
|
|
}
|
|
func writeJSON(w http.ResponseWriter, status int, value any) {
|
|
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
|
w.WriteHeader(status)
|
|
_ = json.NewEncoder(w).Encode(value)
|
|
}
|