Files
mayfly-go/server/internal/msg/msgx/msgx.go

89 lines
1.9 KiB
Go
Raw Normal View History

2025-04-15 21:42:31 +08:00
package msgx
import (
"context"
2025-04-15 21:42:31 +08:00
"fmt"
"mayfly-go/pkg/utils/collx"
"sync"
2025-04-15 21:42:31 +08:00
)
type MsgType int8
type ChannelType string
const (
MsgTypeText MsgType = 1
MsgTypeMarkdown MsgType = 2
MsgTypeHtml MsgType = 3
)
const (
ChannelTypeSiteMsg ChannelType = "siteMsg" // 站内消息
ChannelTypeWs ChannelType = "ws" // websocket
2025-04-15 21:42:31 +08:00
ChannelTypeEmail ChannelType = "email"
ChannelTypeDingBot ChannelType = "dingBot"
ChannelTypeQywxBot ChannelType = "qywxBot"
ChannelTypeFeishuBot ChannelType = "feishuBot"
)
const (
ReceiverKey = "receiver"
)
// Send 发送消息
func Send(ctx context.Context, channel *Channel, msg *Msg) error {
2025-04-15 21:42:31 +08:00
sender, err := GetMsgSender(channel.Type)
if err != nil {
return err
}
return sender.Send(ctx, channel, msg)
2025-04-15 21:42:31 +08:00
}
type Receiver struct {
Extra collx.M
2025-04-15 21:42:31 +08:00
Id uint64 // 接收人ID
2025-04-15 21:42:31 +08:00
Mobile string
Email string
}
type Msg struct {
Title string // 消息title
Type MsgType // 消息类型
Content string // 模板消息内容
Params map[string]any // 消息参数(替换消息中的占位符)
TmplExtra collx.M // 模板消息额外信息
2025-04-15 21:42:31 +08:00
Receivers []Receiver // 消息接收人
}
// Channel 消息发送渠道信息
type Channel struct {
Extra collx.M
2025-04-15 21:42:31 +08:00
Type ChannelType // 渠道类型
Name string
URL string
}
// MsgSender 定义消息发送接口
type MsgSender interface {
// Send 发送消息
Send(ctx context.Context, channel *Channel, msg *Msg) error
2025-04-15 21:42:31 +08:00
}
var messageSenders sync.Map
2025-04-15 21:42:31 +08:00
// RegisterMsgSender 注册消息发送器
func RegisterMsgSender(channel ChannelType, sender MsgSender) {
messageSenders.Store(channel, sender)
2025-04-15 21:42:31 +08:00
}
// GetMsgSender 获取消息发送器
func GetMsgSender(channel ChannelType) (MsgSender, error) {
sender, ok := messageSenders.Load(channel)
2025-04-15 21:42:31 +08:00
if !ok {
return nil, fmt.Errorf("unsupported message channel %s", channel)
}
return sender.(MsgSender), nil
2025-04-15 21:42:31 +08:00
}