package server import ( "github.com/gofiber/fiber/v3" "github.com/pkg/errors" "haitao_watcher/pkg/options" "haitao_watcher/pkg/watcher" "net/url" "time" ) type WatcherSvc struct { ctl *watcher.Controller } func NewWatcherController(ctl *watcher.Controller) *WatcherSvc { return &WatcherSvc{ ctl: ctl, } } func (s *WatcherSvc) RegistryRouter(r fiber.Router) { r.Get("watchers", s.ListWatcherInfo) r.Post("watchers", s.CreateWatcher) r.Delete("watchers/:uid", s.DeleteWatcher) r.Delete("watchers/:uid/status", s.StopWatcher) r.Post("watchers/:uid/status", s.StartWatcher) } func (s *WatcherSvc) ListWatcherInfo(ctx fiber.Ctx) error { var req watcher.ListWatcherInfoRequest if err := ctx.Bind().Query(&req); err != nil { return err } resp, err := s.ctl.List(req) if err != nil { return err } return ctx.JSON(resp) } func (s *WatcherSvc) CreateWatcher(ctx fiber.Ctx) (err error) { var opt options.CoachOutletOption if err = ctx.Bind().JSON(&opt); err != nil { return err } if opt.Interval == 0 { opt.Interval = 5 * time.Minute } if opt.Pid, err = url.QueryUnescape(opt.Pid); err != nil { return } return s.ctl.RunWatcher(&opt) } func (s *WatcherSvc) StopWatcher(ctx fiber.Ctx) (err error) { uid, err := url.QueryUnescape(ctx.Params("uid")) if err != nil { return err } if uid == "" { return errors.New("uid is empty") } return s.ctl.Stop(uid) } func (s *WatcherSvc) StartWatcher(ctx fiber.Ctx) (err error) { uid, err := url.QueryUnescape(ctx.Params("uid")) if err != nil { return err } if uid == "" { return errors.New("uid is empty") } return s.ctl.Start(uid) } func (s *WatcherSvc) DeleteWatcher(ctx fiber.Ctx) error { uid, err := url.QueryUnescape(ctx.Params("uid")) if err != nil { return err } if uid == "" { return errors.New("uid is empty") } return s.ctl.Delete(uid) } func (s *WatcherSvc) SetWatcherPushers(ctx fiber.Ctx) (err error) { var pusherIds []uint if err = ctx.Bind().JSON(&pusherIds); err != nil { return } uid := ctx.Params("uid") if uid == "" { return errors.New("uid is empty") } return s.ctl.SetPushers(uid, pusherIds) }