package handler import ( "net/http" "github.com/company/ai-ops/internal/domain/model" "github.com/company/ai-ops/internal/service" "github.com/company/ai-ops/pkg/errors" "github.com/company/ai-ops/pkg/response" ) // ChannelHandler 是通知渠道 HTTP 处理器 type ChannelHandler struct { service *service.ChannelService } func NewChannelHandler(s *service.ChannelService) *ChannelHandler { return &ChannelHandler{service: s} } func (h *ChannelHandler) RegisterRoutes(mux *http.ServeMux) { mux.HandleFunc("GET /api/v1/ai-ops/channels", h.ListChannels) mux.HandleFunc("GET /api/v1/ai-ops/channels/{id}", h.GetChannel) mux.HandleFunc("POST /api/v1/ai-ops/channels", h.CreateChannel) mux.HandleFunc("PUT /api/v1/ai-ops/channels/{id}", h.UpdateChannel) mux.HandleFunc("DELETE /api/v1/ai-ops/channels/{id}", h.DeleteChannel) mux.HandleFunc("POST /api/v1/ai-ops/channels/test", h.TestChannel) } func (h *ChannelHandler) ListChannels(w http.ResponseWriter, r *http.Request) { channels, err := h.service.List(r.Context()) if err != nil { response.Error(w, errors.Wrap(err, errors.ErrInternal)) return } response.Success(w, channels) } func (h *ChannelHandler) GetChannel(w http.ResponseWriter, r *http.Request) { id := r.PathValue("id") ch, err := h.service.Get(r.Context(), id) if err != nil { response.Error(w, errors.Wrap(err, errors.ErrNotFound)) return } response.Success(w, ch) } func (h *ChannelHandler) CreateChannel(w http.ResponseWriter, r *http.Request) { var ch model.NotificationChannel if err := decodeJSON(r, &ch); err != nil { response.Error(w, errors.ErrBadRequest.WithDetail(map[string]any{"error": err.Error()})) return } if err := h.service.Create(r.Context(), &ch); err != nil { response.Error(w, errors.Wrap(err, errors.ErrBadRequest)) return } w.WriteHeader(http.StatusCreated) response.Success(w, ch) } func (h *ChannelHandler) UpdateChannel(w http.ResponseWriter, r *http.Request) { id := r.PathValue("id") var ch model.NotificationChannel if err := decodeJSON(r, &ch); err != nil { response.Error(w, errors.ErrBadRequest.WithDetail(map[string]any{"error": err.Error()})) return } ch.ID = id if err := h.service.Update(r.Context(), &ch); err != nil { response.Error(w, errors.Wrap(err, errors.ErrBadRequest)) return } response.Success(w, ch) } func (h *ChannelHandler) DeleteChannel(w http.ResponseWriter, r *http.Request) { id := r.PathValue("id") if err := h.service.Delete(r.Context(), id); err != nil { response.Error(w, errors.Wrap(err, errors.ErrInternal)) return } w.WriteHeader(http.StatusNoContent) } func (h *ChannelHandler) TestChannel(w http.ResponseWriter, r *http.Request) { var req struct { ChannelID string `json:"channel_id"` Message string `json:"message"` } if err := decodeJSON(r, &req); err != nil { response.Error(w, errors.ErrBadRequest.WithDetail(map[string]any{"error": err.Error()})) return } response.Success(w, map[string]any{"ok": true}) }