Documentation
¶
Overview ¶
Package notification provides a unified, provider-agnostic notification framework supporting email, SMS, instant messaging (IM), webhooks, and in-app inbox messages.
Architecture ¶
The core abstraction is the Channel interface. Each channel type (email, SMS, IM, webhook, inbox) implements this interface with its own provider subpackages:
- notification/email — SMTP and cloud email providers
- notification/sms — 17+ SMS providers (Aliyun, Tencent, Twilio, ...)
- notification/im — WeCom, Feishu/Lark
- notification/webhook — HTTP callback dispatcher with retry
- notification/inbox — In-app notification store
A Dispatcher manages multiple channels and provides multi-channel failover: if one channel fails, the next enabled channel is tried.
Decoupled design ¶
Unlike monolithic notification systems, this package has no hard dependency on a specific database or ORM. Logging and template loading are pluggable via the LogStore and TemplateStore interfaces. Applications wire concrete implementations (e.g. a gorm-backed store) at startup.
Quick start ¶
dispatcher := notification.NewDispatcher()
dispatcher.AddChannel("email-primary", emailChannel)
dispatcher.AddChannel("email-backup", emailBackupChannel)
err := dispatcher.Send(ctx, notification.Message{
Type: notification.TypeEmail,
To: "user@example.com",
Subject: "Welcome",
Body: "Hello!",
})
Index ¶
- type BaseChannel
- type Channel
- type ChannelFunc
- type Dispatcher
- func (d *Dispatcher) AddChannel(ch Channel)
- func (d *Dispatcher) ChannelNames() []string
- func (d *Dispatcher) Channels() []Channel
- func (d *Dispatcher) EnabledChannelCount(typ MessageType) int
- func (d *Dispatcher) RemoveChannel(name string) bool
- func (d *Dispatcher) Send(ctx context.Context, msg Message) error
- func (d *Dispatcher) SendToType(ctx context.Context, typ MessageType, to, subject, body string) error
- func (d *Dispatcher) SetLogStore(store LogStore)
- type LogEntry
- type LogStore
- type Message
- func NewEmailMessage(to, subject, body string) Message
- func NewIMMessage(title, content string) Message
- func NewInboxMessage(userID, title, content string) Message
- func NewPushMessage(token, title, body string) Message
- func NewSMSMessage(phone, content string) Message
- func NewWebhookMessage(event, url string, data map[string]any) Message
- type MessageType
- type NoopLogStore
- type TemplateStore
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type BaseChannel ¶
type BaseChannel struct {
ChannelName string
ChannelType MessageType
IsEnabled bool
}
BaseChannel is a reusable base struct for channel implementations. Embed it in a concrete channel struct to get Name/Type/Enabled boilerplate for free.
func (*BaseChannel) Enabled ¶
func (b *BaseChannel) Enabled() bool
func (*BaseChannel) Name ¶
func (b *BaseChannel) Name() string
func (*BaseChannel) Type ¶
func (b *BaseChannel) Type() MessageType
type Channel ¶
type Channel interface {
// Name returns a human-readable channel identifier (e.g. "email-primary").
Name() string
// Type returns the channel type (email, sms, im, webhook, inbox).
Type() MessageType
// Send delivers a message through this channel. Returns an error
// if delivery fails; the Dispatcher may try the next channel.
Send(ctx context.Context, msg Message) error
// Enabled reports whether this channel is currently active.
Enabled() bool
}
Channel is the unified notification channel interface. Each provider (email/SMS/IM/webhook/inbox) implements this interface.
type ChannelFunc ¶
type ChannelFunc struct {
ChannelName string
ChannelType MessageType
ChannelEnabled bool
SendFunc func(ctx context.Context, msg Message) error
// contains filtered or unexported fields
}
ChannelFunc is a function adapter for the Channel interface. It is useful for creating simple channels without defining a full struct.
func NewChannelFunc ¶
func NewChannelFunc(name string, typ MessageType, enabled bool, send func(ctx context.Context, msg Message) error) *ChannelFunc
NewChannelFunc creates a simple channel from a function.
func (*ChannelFunc) Enabled ¶
func (c *ChannelFunc) Enabled() bool
Enabled reports whether the channel is active.
func (*ChannelFunc) Send ¶
func (c *ChannelFunc) Send(ctx context.Context, msg Message) error
Send calls the configured send function.
func (*ChannelFunc) SetEnabled ¶
func (c *ChannelFunc) SetEnabled(enabled bool)
SetEnabled dynamically enables or disables the channel.
type Dispatcher ¶
type Dispatcher struct {
// contains filtered or unexported fields
}
Dispatcher manages multiple notification channels and provides multi-channel failover. When a Send is called, the dispatcher tries each enabled channel of the matching type in order until one succeeds.
func NewDispatcher ¶
func NewDispatcher() *Dispatcher
NewDispatcher creates a new Dispatcher with no channels. A NoopLogStore is used by default.
func NewDispatcherWithStore ¶
func NewDispatcherWithStore(store LogStore) *Dispatcher
NewDispatcherWithStore creates a Dispatcher with a custom LogStore.
func (*Dispatcher) AddChannel ¶
func (d *Dispatcher) AddChannel(ch Channel)
AddChannel registers a channel. Channels are tried in registration order for their respective message types.
func (*Dispatcher) ChannelNames ¶
func (d *Dispatcher) ChannelNames() []string
ChannelNames returns the names of all registered channels.
func (*Dispatcher) Channels ¶
func (d *Dispatcher) Channels() []Channel
Channels returns a copy of the registered channels.
func (*Dispatcher) EnabledChannelCount ¶
func (d *Dispatcher) EnabledChannelCount(typ MessageType) int
EnabledChannelCount returns the number of enabled channels for a given message type.
func (*Dispatcher) RemoveChannel ¶
func (d *Dispatcher) RemoveChannel(name string) bool
RemoveChannel removes a channel by name. Returns true if found.
func (*Dispatcher) Send ¶
func (d *Dispatcher) Send(ctx context.Context, msg Message) error
Send dispatches a message to all enabled channels of the matching type. It tries channels in order and returns nil on the first success. If all channels fail, it returns a combined error.
func (*Dispatcher) SendToType ¶
func (d *Dispatcher) SendToType(ctx context.Context, typ MessageType, to, subject, body string) error
SendToType is a convenience that constructs a message of the given type and sends it.
func (*Dispatcher) SetLogStore ¶
func (d *Dispatcher) SetLogStore(store LogStore)
SetLogStore replaces the log store.
type LogEntry ¶
type LogEntry struct {
ID string // unique log ID
ChannelName string // channel that handled the send
Type MessageType
To string // recipient
Subject string // subject or title
Content string // body or content
Status string // "sent", "failed", "pending"
ErrorMsg string // error message if failed
MessageID string // provider message ID if available
IPAddress string // client IP for audit
RetryCount int // number of retries attempted
SentAt time.Time // when the send was attempted
CreatedAt time.Time // when the log was created
}
LogEntry represents a notification delivery log record.
type LogStore ¶
type LogStore interface {
// CreateLog persists a log entry.
CreateLog(entry LogEntry) error
// UpdateStatus updates the status of a log entry by ID.
UpdateStatus(id, status, errorMsg string) error
// GetLog retrieves a log entry by ID.
GetLog(id string) (*LogEntry, error)
}
LogStore is the pluggable persistence interface for notification logs. Applications provide a concrete implementation (e.g. gorm-backed). A nil/no-op store is acceptable for testing.
type Message ¶
type Message struct {
Type MessageType // channel type (email, sms, im, webhook, inbox)
To string // recipient (email address, phone number, user ID, URL)
Subject string // subject line (email, IM title)
Body string // plain-text body
HTML string // HTML body (email)
Data map[string]any // template variables or provider-specific data
Extras map[string]any // additional provider-specific fields
// SMS-specific
PhoneNumber string // full phone number with country code
CountryCode int // country code (e.g. 86 for China)
Template string // provider template ID
SignName string // SMS signature name
// IM-specific
Title string // IM message title
Content string // IM message content (markdown or plain)
// Webhook-specific
Event string // webhook event name
URL string // webhook target URL
// Inbox-specific
UserID string // target user ID
ActionURL string // optional action link
ActionLabel string // optional action button label
// Metadata
Locale string // locale for i18n template rendering
IPAddress string // client IP for audit logging
Timestamp time.Time
}
Message is the unified notification payload. Not all fields are relevant for every channel type; providers ignore fields they don't use.
func NewEmailMessage ¶
NewEmailMessage is a convenience constructor for email messages.
func NewIMMessage ¶
NewIMMessage is a convenience constructor for IM messages.
func NewInboxMessage ¶
NewInboxMessage is a convenience constructor for in-app inbox messages.
func NewPushMessage ¶
NewPushMessage is a convenience constructor for mobile push messages. The device token is placed in both To and Data so the push channel can recover it from either field.
func NewSMSMessage ¶
NewSMSMessage is a convenience constructor for SMS messages.
type MessageType ¶
type MessageType string
MessageType identifies the notification channel type.
const ( TypeEmail MessageType = "email" TypeSMS MessageType = "sms" TypeIM MessageType = "im" TypeWebhook MessageType = "webhook" TypeInbox MessageType = "inbox" TypePush MessageType = "push" )
type NoopLogStore ¶
type NoopLogStore struct{}
NoopLogStore is a no-op LogStore for testing or when persistence is not required.
func (NoopLogStore) CreateLog ¶
func (NoopLogStore) CreateLog(entry LogEntry) error
func (NoopLogStore) UpdateStatus ¶
func (NoopLogStore) UpdateStatus(id, status, errorMsg string) error
type TemplateStore ¶
type TemplateStore interface {
// LoadTemplate returns the subject and body for a template code
// and locale. The body may be HTML or plain text.
LoadTemplate(code, locale string) (subject, body string, err error)
}
TemplateStore is the pluggable template loading interface.