pusher/pushers/controller.go
timerzz 4ec0cd1564
Some checks failed
Build image / build (push) Failing after 4m48s
feat 测试
2024-05-20 17:57:25 +08:00

68 lines
1.5 KiB
Go

package pushers
import (
"context"
"gitea.timerzz.com/kedaya_haitao/pusher/biz/dal/postgres"
"gitea.timerzz.com/kedaya_haitao/pusher/kitex_gen/config"
"github.com/bytedance/sonic"
"golang.org/x/sync/errgroup"
"sync"
)
func Init() {
c = &Controller{
pushers: make(map[int64]Pusher),
}
}
func Push(ctx context.Context, ids []int64, title, content string) error {
return c.Push(ctx, ids, title, content)
}
type Pusher interface {
Push(ctx context.Context, title, content string) error
}
type Controller struct {
pushers map[int64]Pusher
l sync.Mutex
}
var c *Controller
func (c *Controller) Push(ctx context.Context, ids []int64, title, content string) error {
wg, sub := errgroup.WithContext(ctx)
for _, id := range ids {
var i = id
wg.Go(func() error {
if pusher, ok := c.pushers[i]; ok {
return pusher.Push(sub, title, content)
} else {
var cfg config.PusherConfig
if err := postgres.DB.Where("id = ?", i).Find(&cfg).Error; err != nil {
return err
}
c.l.Lock()
c.pushers[cfg.Id] = NewPusher(cfg)
c.l.Unlock()
return c.pushers[cfg.Id].Push(sub, title, content)
}
})
}
return wg.Wait()
}
func NewPusher(cfg config.PusherConfig) Pusher {
switch cfg.Type {
case config.PusherConfigType_AnPush:
var opt config.AnPush
_ = sonic.UnmarshalString(cfg.Option, &opt)
return NewAnPush(&opt)
case config.PusherConfigType_Email:
var opt config.EmailPush
_ = sonic.UnmarshalString(cfg.Option, &opt)
return NewEmailPusher(&opt)
}
return nil
}