Documentation
¶
Index ¶
- func FormatVerificationEmail(code string, locale string) (subject, body string)
- func FormatVerificationEmailWithMinutes(code string, locale string, minutes int) (subject, body string)
- func FormatVerificationSMS(code string, locale string) string
- func FormatVerificationSMSWithMinutes(code string, locale string, minutes int) string
- func IsProviderError(err error) bool
- func RegisterGlobal(provider Provider) error
- type Channel
- type DefaultSMTPDialer
- type ErrorReason
- type HTTPConfig
- type HTTPProvider
- type HTTPSendRequest
- type HTTPSendResponse
- type IdempotencyConfig
- type IdempotencyStore
- type IdempotentProvider
- type MemoryIdempotencyStore
- type Message
- func (m *Message) AddMetadata(key, value string) *Message
- func (m *Message) Clone() *Message
- func (m *Message) String() string
- func (m *Message) Validate() error
- func (m *Message) WithBody(body string) *Message
- func (m *Message) WithCode(code string) *Message
- func (m *Message) WithIdempotencyKey(key string) *Message
- func (m *Message) WithLocale(locale string) *Message
- func (m *Message) WithMetadata(metadata map[string]string) *Message
- func (m *Message) WithParam(key, value string) *Message
- func (m *Message) WithParams(params map[string]string) *Message
- func (m *Message) WithSubject(subject string) *Message
- func (m *Message) WithTemplate(template string) *Message
- type MultiChannelProvider
- type Provider
- func GetGlobal(channel Channel) (Provider, error)
- func HTTPProviderFactory(config map[string]string) (Provider, error)
- func NewHTTPProviderFromMap(configMap map[string]string) (Provider, error)
- func NewSMTPProviderFromMap(configMap map[string]string) (Provider, error)
- func SMTPProviderFactory(config map[string]string) (Provider, error)
- func WrapWithIdempotency(provider Provider, store IdempotencyStore, ttl time.Duration) Provider
- func WrapWithRetry(provider Provider, maxRetries int, retryDelay time.Duration) Provider
- type ProviderError
- func ErrIdempotencyConflict(message string) *ProviderError
- func ErrInvalidConfig(message string) *ProviderError
- func ErrInvalidDestination(message string) *ProviderError
- func ErrNotRegistered(channel Channel) *ProviderError
- func ErrProviderDown(message string, err error) *ProviderError
- func ErrRateLimited(message string) *ProviderError
- func ErrSendFailed(message string, err error) *ProviderError
- func ErrTimeout(message string, err error) *ProviderError
- func ErrUnauthorized(message string) *ProviderError
- func ErrValidationFailed(message string) *ProviderError
- func NewProviderError(reason ErrorReason, message string) *ProviderError
- func NormalizeError(err error, channel Channel, providerName string) *ProviderError
- type ProviderFactory
- type Registry
- func (r *Registry) Channels() []Channel
- func (r *Registry) Clear()
- func (r *Registry) CreateProvider(name string, config map[string]string) (Provider, error)
- func (r *Registry) Get(channel Channel) (Provider, error)
- func (r *Registry) GetProvider(channel Channel) (Provider, error)
- func (r *Registry) Has(channel Channel) bool
- func (r *Registry) HasFactory(name string) bool
- func (r *Registry) Providers() []Provider
- func (r *Registry) Register(provider Provider) error
- func (r *Registry) RegisterFactory(name string, factory ProviderFactory) error
- func (r *Registry) Send(ctx context.Context, channel Channel, msg *Message) (*SendResult, error)
- func (r *Registry) Unregister(channel Channel)
- func (r *Registry) UnregisterFactory(name string)
- type RetryConfig
- type RetryProvider
- type RetrySender
- type SMTPClient
- type SMTPConfig
- type SMTPDialer
- type SMTPProvider
- type SendResult
- type Sender
- type SimpleTemplateRenderer
- type TemplateRenderer
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func FormatVerificationEmail ¶
FormatVerificationEmail formats a verification code email (expiry fixed at 5 minutes). Returns subject and body based on locale. Use FormatVerificationEmailWithMinutes for custom expiry.
func FormatVerificationEmailWithMinutes ¶ added in v1.1.0
func FormatVerificationEmailWithMinutes(code string, locale string, minutes int) (subject, body string)
FormatVerificationEmailWithMinutes formats a verification code email with custom expiry in minutes. Returns subject and body based on locale. Used by Herald template when purpose is "login".
func FormatVerificationSMS ¶
FormatVerificationSMS formats a verification code SMS (expiry fixed at 5 minutes). Use FormatVerificationSMSWithMinutes for custom expiry.
func FormatVerificationSMSWithMinutes ¶ added in v1.1.0
FormatVerificationSMSWithMinutes formats a verification code SMS with custom expiry in minutes. Used by Herald template when purpose is "login".
func IsProviderError ¶
IsProviderError checks if the error is a ProviderError
func RegisterGlobal ¶
RegisterGlobal registers a provider in the global registry
Types ¶
type Channel ¶
type Channel string
Channel represents the delivery channel type
const ( // ChannelSMS represents SMS delivery channel ChannelSMS Channel = "sms" // ChannelEmail represents email delivery channel ChannelEmail Channel = "email" // ChannelHTTP represents generic HTTP API channel (for extensibility) ChannelHTTP Channel = "http" // ChannelDingTalk represents DingTalk work notification (via herald-dingtalk HTTP service) ChannelDingTalk Channel = "dingtalk" )
func SupportedChannels ¶
func SupportedChannels() []Channel
SupportedChannels returns all supported channels
type DefaultSMTPDialer ¶
type DefaultSMTPDialer struct{}
DefaultSMTPDialer uses the standard library for SMTP
type ErrorReason ¶
type ErrorReason string
Error reason codes for provider operations
const ( // ReasonSendFailed indicates the send operation failed ReasonSendFailed ErrorReason = "send_failed" // ReasonProviderDown indicates the provider is unavailable ReasonProviderDown ErrorReason = "provider_down" // ReasonInvalidConfig indicates invalid provider configuration ReasonInvalidConfig ErrorReason = "invalid_config" // ReasonRateLimited indicates the provider rate limited the request ReasonRateLimited ErrorReason = "rate_limited" // ReasonInvalidDestination indicates the destination is invalid ReasonInvalidDestination ErrorReason = "invalid_destination" // ReasonTimeout indicates the request timed out ReasonTimeout ErrorReason = "timeout" ReasonUnauthorized ErrorReason = "unauthorized" // ReasonNotRegistered indicates no provider is registered for the channel ReasonNotRegistered ErrorReason = "not_registered" // ReasonValidationFailed indicates provider validation failed ReasonValidationFailed ErrorReason = "validation_failed" // ReasonIdempotencyConflict indicates an idempotency conflict ReasonIdempotencyConflict ErrorReason = "idempotency_conflict" )
func GetErrorReason ¶
func GetErrorReason(err error) (ErrorReason, bool)
GetErrorReason extracts the error reason from a ProviderError
func (ErrorReason) String ¶
func (r ErrorReason) String() string
String returns the string representation of the error reason
type HTTPConfig ¶
type HTTPConfig struct {
// BaseURL is the API base URL
BaseURL string
// SendEndpoint is the send endpoint path (default: /v1/send)
SendEndpoint string
// APIKey is the API key for authentication
APIKey string
// APIKeyHeader is the header name for API key (default: X-API-Key)
APIKeyHeader string
// Timeout is the request timeout
Timeout time.Duration
// Headers are additional headers to include in requests
Headers map[string]string
// ChannelType is the channel type this provider handles
ChannelType Channel
// ProviderName is the name of this provider instance
ProviderName string
}
HTTPConfig contains HTTP API provider configuration
func DefaultHTTPConfig ¶
func DefaultHTTPConfig() *HTTPConfig
DefaultHTTPConfig returns default HTTP configuration
func (*HTTPConfig) Validate ¶
func (c *HTTPConfig) Validate() error
Validate validates the HTTP configuration
type HTTPProvider ¶
type HTTPProvider struct {
// contains filtered or unexported fields
}
HTTPProvider implements message sending via HTTP API This is a generic provider for external messaging APIs
func NewHTTPProvider ¶
func NewHTTPProvider(config *HTTPConfig) (*HTTPProvider, error)
NewHTTPProvider creates a new HTTP API provider
func (*HTTPProvider) Channel ¶
func (p *HTTPProvider) Channel() Channel
Channel returns the channel type
func (*HTTPProvider) Send ¶
func (p *HTTPProvider) Send(ctx context.Context, msg *Message) (*SendResult, error)
Send sends a message via HTTP API
func (*HTTPProvider) SetHTTPClient ¶
func (p *HTTPProvider) SetHTTPClient(client *http.Client)
SetHTTPClient sets a custom HTTP client
func (*HTTPProvider) Validate ¶
func (p *HTTPProvider) Validate() error
Validate checks if the provider is properly configured
type HTTPSendRequest ¶
type HTTPSendRequest struct {
Channel string `json:"channel"`
To string `json:"to"`
Template string `json:"template,omitempty"`
Params map[string]string `json:"params,omitempty"`
Subject string `json:"subject,omitempty"`
Body string `json:"body,omitempty"`
Locale string `json:"locale,omitempty"`
IdempotencyKey string `json:"idempotency_key"`
TimeoutSeconds int `json:"timeout_seconds,omitempty"`
}
HTTPSendRequest is the request body for the HTTP send API
type HTTPSendResponse ¶
type HTTPSendResponse struct {
OK bool `json:"ok"`
MessageID string `json:"message_id,omitempty"`
Provider string `json:"provider,omitempty"`
ErrorCode string `json:"error_code,omitempty"`
ErrorMessage string `json:"error_message,omitempty"`
}
HTTPSendResponse is the response body from the HTTP send API
type IdempotencyConfig ¶
type IdempotencyConfig struct {
// Store is the idempotency store (default: in-memory)
Store IdempotencyStore
// TTL is the cache TTL for idempotency records
TTL time.Duration
}
IdempotencyConfig contains idempotency configuration
func DefaultIdempotencyConfig ¶
func DefaultIdempotencyConfig() *IdempotencyConfig
DefaultIdempotencyConfig returns default idempotency configuration
type IdempotencyStore ¶
type IdempotencyStore interface {
// Get retrieves a cached result for the given key
Get(ctx context.Context, key string) (*SendResult, bool, error)
// Set stores a result with the given key and TTL
Set(ctx context.Context, key string, result *SendResult, ttl time.Duration) error
// Delete removes a cached result
Delete(ctx context.Context, key string) error
}
IdempotencyStore defines the interface for storing idempotency records
type IdempotentProvider ¶
type IdempotentProvider struct {
// contains filtered or unexported fields
}
IdempotentProvider wraps a provider with idempotency support
func NewIdempotentProvider ¶
func NewIdempotentProvider(provider Provider, config *IdempotencyConfig) *IdempotentProvider
NewIdempotentProvider wraps a provider with idempotency support
func (*IdempotentProvider) Channel ¶
func (p *IdempotentProvider) Channel() Channel
Channel returns the channel type
func (*IdempotentProvider) Name ¶
func (p *IdempotentProvider) Name() string
Name returns the provider name
func (*IdempotentProvider) Send ¶
func (p *IdempotentProvider) Send(ctx context.Context, msg *Message) (*SendResult, error)
Send sends a message with idempotency support
func (*IdempotentProvider) Validate ¶
func (p *IdempotentProvider) Validate() error
Validate checks if the provider is properly configured
type MemoryIdempotencyStore ¶
type MemoryIdempotencyStore struct {
// contains filtered or unexported fields
}
MemoryIdempotencyStore is an in-memory idempotency store
func NewMemoryIdempotencyStore ¶
func NewMemoryIdempotencyStore() *MemoryIdempotencyStore
NewMemoryIdempotencyStore creates a new in-memory idempotency store
func (*MemoryIdempotencyStore) Delete ¶
func (s *MemoryIdempotencyStore) Delete(ctx context.Context, key string) error
Delete removes a cached result
func (*MemoryIdempotencyStore) Get ¶
func (s *MemoryIdempotencyStore) Get(ctx context.Context, key string) (*SendResult, bool, error)
Get retrieves a cached result for the given key
func (*MemoryIdempotencyStore) Set ¶
func (s *MemoryIdempotencyStore) Set(ctx context.Context, key string, result *SendResult, ttl time.Duration) error
Set stores a result with the given key and TTL
type Message ¶
type Message struct {
// To is the recipient address (email address or phone number)
To string
// Subject is the message subject (primarily for email)
Subject string
// Body is the message body content
Body string
// Template is the template name/identifier (for templated messages)
Template string
// Params are template parameters/variables
Params map[string]string
// Code is the verification code (for OTP messages)
Code string
// Locale is the locale for message formatting (e.g., "en-US", "zh-CN")
Locale string
// IdempotencyKey is the key for idempotency (prevents duplicate sends)
IdempotencyKey string
// Metadata contains additional provider-specific data
Metadata map[string]string
}
Message represents a message to be sent via a provider
func BuildVerificationMessage ¶
BuildVerificationMessage creates a verification code message
func NewMessage ¶
NewMessage creates a new Message with the required destination
func (*Message) AddMetadata ¶
AddMetadata adds a single metadata entry
func (*Message) String ¶
String returns a string representation (safe for logging, without sensitive data)
func (*Message) WithIdempotencyKey ¶
WithIdempotencyKey sets the idempotency key
func (*Message) WithLocale ¶
WithLocale sets the locale
func (*Message) WithMetadata ¶
WithMetadata sets additional metadata
func (*Message) WithParams ¶
WithParams sets the template parameters
func (*Message) WithSubject ¶
WithSubject sets the message subject
func (*Message) WithTemplate ¶
WithTemplate sets the template name
type MultiChannelProvider ¶
type MultiChannelProvider interface {
Provider
// Channels returns all channels this provider supports
Channels() []Channel
}
MultiChannelProvider is a provider that supports multiple channels
type Provider ¶
type Provider interface {
// Send sends a message via the provider
Send(ctx context.Context, msg *Message) (*SendResult, error)
// Channel returns the channel type this provider supports
Channel() Channel
// Name returns the provider's name (e.g., "smtp", "aliyun", "twilio")
Name() string
// Validate checks if the provider is properly configured
Validate() error
}
Provider is the interface for message providers
func HTTPProviderFactory ¶
HTTPProviderFactory is the factory for HTTP providers
func NewHTTPProviderFromMap ¶
NewHTTPProviderFromMap creates an HTTP provider from a configuration map
func NewSMTPProviderFromMap ¶
NewSMTPProviderFromMap creates an SMTP provider from a configuration map
func SMTPProviderFactory ¶
SMTPProviderFactory is the factory for SMTP providers
func WrapWithIdempotency ¶
func WrapWithIdempotency(provider Provider, store IdempotencyStore, ttl time.Duration) Provider
WrapWithIdempotency wraps a provider with idempotency support
type ProviderError ¶
type ProviderError struct {
Reason ErrorReason
Message string
ProviderName string
Channel Channel
Err error // Underlying error
}
ProviderError represents a provider operation error
func ErrIdempotencyConflict ¶
func ErrIdempotencyConflict(message string) *ProviderError
ErrIdempotencyConflict creates an idempotency conflict error
func ErrInvalidConfig ¶
func ErrInvalidConfig(message string) *ProviderError
ErrInvalidConfig creates an invalid configuration error
func ErrInvalidDestination ¶
func ErrInvalidDestination(message string) *ProviderError
ErrInvalidDestination creates an invalid destination error
func ErrNotRegistered ¶
func ErrNotRegistered(channel Channel) *ProviderError
ErrNotRegistered creates a not registered error
func ErrProviderDown ¶
func ErrProviderDown(message string, err error) *ProviderError
ErrProviderDown creates a provider unavailable error
func ErrRateLimited ¶
func ErrRateLimited(message string) *ProviderError
ErrRateLimited creates a rate limited error
func ErrSendFailed ¶
func ErrSendFailed(message string, err error) *ProviderError
ErrSendFailed creates a send failure error
func ErrTimeout ¶
func ErrTimeout(message string, err error) *ProviderError
ErrTimeout creates a timeout error
func ErrUnauthorized ¶
func ErrUnauthorized(message string) *ProviderError
ErrUnauthorized creates an unauthorized error
func ErrValidationFailed ¶
func ErrValidationFailed(message string) *ProviderError
ErrValidationFailed creates a validation failed error
func NewProviderError ¶
func NewProviderError(reason ErrorReason, message string) *ProviderError
NewProviderError creates a new ProviderError
func NormalizeError ¶
func NormalizeError(err error, channel Channel, providerName string) *ProviderError
NormalizeError normalizes any error to a ProviderError
func (*ProviderError) Error ¶
func (e *ProviderError) Error() string
Error implements the error interface
func (*ProviderError) Unwrap ¶
func (e *ProviderError) Unwrap() error
Unwrap returns the underlying error
func (*ProviderError) WithError ¶
func (e *ProviderError) WithError(err error) *ProviderError
WithError adds an underlying error
func (*ProviderError) WithProvider ¶
func (e *ProviderError) WithProvider(name string, channel Channel) *ProviderError
WithProvider adds provider information to the error
type ProviderFactory ¶
ProviderFactory creates a provider instance
type Registry ¶
type Registry struct {
// contains filtered or unexported fields
}
Registry manages available providers
func GlobalRegistry ¶
func GlobalRegistry() *Registry
GlobalRegistry returns the global registry instance
func (*Registry) Clear ¶
func (r *Registry) Clear()
Clear removes all registered providers and factories
func (*Registry) CreateProvider ¶
CreateProvider creates a provider using a registered factory
func (*Registry) GetProvider ¶
GetProvider is an alias for Get (for backward compatibility)
func (*Registry) HasFactory ¶
HasFactory checks if a factory is registered
func (*Registry) RegisterFactory ¶
func (r *Registry) RegisterFactory(name string, factory ProviderFactory) error
RegisterFactory registers a provider factory by name
func (*Registry) Unregister ¶
Unregister removes a provider for a channel
func (*Registry) UnregisterFactory ¶
UnregisterFactory removes a factory by name
type RetryConfig ¶
type RetryConfig struct {
// MaxRetries is the maximum number of retry attempts
MaxRetries int
// RetryDelay is the initial delay between retries
RetryDelay time.Duration
// MaxRetryDelay is the maximum delay between retries
MaxRetryDelay time.Duration
// BackoffMultiplier is the multiplier for exponential backoff
BackoffMultiplier float64
// RetryableReasons are error reasons that should trigger a retry
RetryableReasons []ErrorReason
}
RetryConfig contains retry configuration
func DefaultRetryConfig ¶
func DefaultRetryConfig() *RetryConfig
DefaultRetryConfig returns default retry configuration
func (*RetryConfig) CalculateDelay ¶
func (c *RetryConfig) CalculateDelay(attempt int) time.Duration
CalculateDelay calculates the delay for the next retry attempt using exponential backoff
func (*RetryConfig) IsRetryable ¶
func (c *RetryConfig) IsRetryable(err error) bool
IsRetryable checks if an error should trigger a retry
type RetryProvider ¶
type RetryProvider struct {
// contains filtered or unexported fields
}
RetryProvider wraps a provider with retry support
func NewRetryProvider ¶
func NewRetryProvider(provider Provider, config *RetryConfig) *RetryProvider
NewRetryProvider wraps a provider with retry support
func (*RetryProvider) Channel ¶
func (p *RetryProvider) Channel() Channel
Channel returns the channel type
func (*RetryProvider) Send ¶
func (p *RetryProvider) Send(ctx context.Context, msg *Message) (*SendResult, error)
Send sends a message with retry support
func (*RetryProvider) Validate ¶
func (p *RetryProvider) Validate() error
Validate checks if the provider is properly configured
type RetrySender ¶
type RetrySender struct {
// contains filtered or unexported fields
}
RetrySender wraps a Sender with retry support
func NewRetrySender ¶
func NewRetrySender(sender Sender, config *RetryConfig) *RetrySender
NewRetrySender wraps a sender with retry support
func (*RetrySender) Send ¶
func (s *RetrySender) Send(ctx context.Context, channel Channel, msg *Message) (*SendResult, error)
Send sends a message with retry support
type SMTPClient ¶
type SMTPClient interface {
Auth(a interface{}) error
Mail(from string) error
Rcpt(to string) error
Data() (interface {
Write([]byte) (int, error)
Close() error
}, error)
Quit() error
Close() error
}
SMTPClient is the interface for SMTP client operations
type SMTPConfig ¶
type SMTPConfig struct {
// Host is the SMTP server host
Host string
// Port is the SMTP server port
Port int
// Username is the SMTP authentication username
Username string
// Password is the SMTP authentication password
Password string
// From is the sender email address
From string
// FromName is the sender display name (optional)
FromName string
// UseTLS enables TLS connection
UseTLS bool
// UseStartTLS enables STARTTLS
UseStartTLS bool
// SkipTLSVerify skips TLS certificate verification (not recommended)
SkipTLSVerify bool
// Timeout is the connection timeout
Timeout time.Duration
}
SMTPConfig contains SMTP provider configuration
func DefaultSMTPConfig ¶
func DefaultSMTPConfig() *SMTPConfig
DefaultSMTPConfig returns default SMTP configuration
func (*SMTPConfig) Validate ¶
func (c *SMTPConfig) Validate() error
Validate validates the SMTP configuration
type SMTPDialer ¶
type SMTPDialer interface {
// DialPlain dials SMTP server without encryption
DialPlain(addr string, auth interface{}, from string, to []string, body []byte) error
// DialTLS dials SMTP server with TLS
DialTLS(addr string, tlsConfig interface{}, host string) (SMTPClient, error)
// DialStartTLS dials SMTP server and upgrades to TLS
DialStartTLS(addr string, tlsConfig interface{}) (SMTPClient, error)
}
SMTPDialer is the interface for SMTP connection operations
type SMTPProvider ¶
type SMTPProvider struct {
// contains filtered or unexported fields
}
SMTPProvider implements email sending via SMTP
func NewSMTPProvider ¶
func NewSMTPProvider(config *SMTPConfig) (*SMTPProvider, error)
NewSMTPProvider creates a new SMTP provider
func (*SMTPProvider) Channel ¶
func (p *SMTPProvider) Channel() Channel
Channel returns the channel type
func (*SMTPProvider) Send ¶
func (p *SMTPProvider) Send(ctx context.Context, msg *Message) (*SendResult, error)
Send sends an email via SMTP
func (*SMTPProvider) SetDialer ¶
func (p *SMTPProvider) SetDialer(dialer SMTPDialer)
SetDialer sets a custom dialer for testing
func (*SMTPProvider) Validate ¶
func (p *SMTPProvider) Validate() error
Validate checks if the provider is properly configured
type SendResult ¶
type SendResult struct {
// OK indicates if the send was successful
OK bool
// MessageID is the provider's message ID (if available)
MessageID string
// Provider is the name of the provider that handled the request
Provider string
// Channel is the channel used for sending
Channel Channel
// Timestamp is when the message was sent
Timestamp time.Time
// Metadata contains additional result data from the provider
Metadata map[string]string
// Error contains error details if OK is false
Error *ProviderError
}
SendResult represents the result of a send operation
func NewFailureResult ¶
func NewFailureResult(provider string, channel Channel, err *ProviderError) *SendResult
NewFailureResult creates a failed send result
func NewSuccessResult ¶
func NewSuccessResult(provider string, channel Channel, messageID string) *SendResult
NewSuccessResult creates a successful send result
func SendGlobal ¶
SendGlobal sends a message using the global registry
func (*SendResult) GetError ¶
func (r *SendResult) GetError() error
GetError returns the error if the result is a failure
func (*SendResult) WithMetadata ¶
func (r *SendResult) WithMetadata(key, value string) *SendResult
WithMetadata adds metadata to the result
type Sender ¶
type Sender interface {
// Send sends a message using the appropriate provider
Send(ctx context.Context, channel Channel, msg *Message) (*SendResult, error)
}
Sender is a simplified interface for sending messages
type SimpleTemplateRenderer ¶
type SimpleTemplateRenderer struct {
// contains filtered or unexported fields
}
SimpleTemplateRenderer is a simple template renderer using string replacement
func NewSimpleTemplateRenderer ¶
func NewSimpleTemplateRenderer() *SimpleTemplateRenderer
NewSimpleTemplateRenderer creates a new simple template renderer
func (*SimpleTemplateRenderer) WithDelimiters ¶
func (r *SimpleTemplateRenderer) WithDelimiters(left, right string) *SimpleTemplateRenderer
WithDelimiters sets custom delimiters