86 lines
1.8 KiB
Go
86 lines
1.8 KiB
Go
package interfaces
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
)
|
|
|
|
|
|
|
|
type EmailInterface interface {
|
|
SetOption(ctx context.Context, opt ...Option) (EmailInterface, error) // 初始化
|
|
GetEmailType() EmailType
|
|
// Send 发送邮件
|
|
Send(ctx context.Context, params Message) error
|
|
}
|
|
|
|
type EmailFactoryInterface interface {
|
|
Register(EmailInterface) // 注册一个接口
|
|
SetOption(opt ...Option) // 针对已注册的进行初始化
|
|
GetEmail(EmailType) (EmailInterface, error)
|
|
UnRegister(EmailType)
|
|
}
|
|
|
|
type DefaultEmail struct {
|
|
Options emailOption
|
|
EmailType EmailType
|
|
}
|
|
|
|
func NewDefaultEmail() *DefaultEmail {
|
|
return &DefaultEmail{
|
|
Options: DefaultOptions(),
|
|
EmailType: "DefaultEmail",
|
|
}
|
|
}
|
|
|
|
func (l *DefaultEmail) SetOption(ctx context.Context, opt ...Option) (EmailInterface, error) {
|
|
// 深复制l并且返回新的
|
|
newL := *l
|
|
|
|
for _, o := range opt {
|
|
o(&newL.Options)
|
|
}
|
|
|
|
return &newL, nil
|
|
}
|
|
|
|
func (l *DefaultEmail) GetEmailType() EmailType {
|
|
return l.EmailType
|
|
}
|
|
|
|
func (l *DefaultEmail) Send(ctx context.Context, params Message) error {
|
|
return errors.New("not implemented")
|
|
}
|
|
|
|
type DefaultEmailFactory struct {
|
|
Emails map[EmailType]EmailInterface
|
|
}
|
|
|
|
func NewDefaultEmailFactory() *DefaultEmailFactory {
|
|
return &DefaultEmailFactory{
|
|
Emails: make(map[EmailType]EmailInterface),
|
|
}
|
|
}
|
|
|
|
func (l *DefaultEmailFactory) Register(email EmailInterface) {
|
|
l.Emails[email.GetEmailType()] = email
|
|
}
|
|
|
|
func (l *DefaultEmailFactory) SetOption(opt ...Option) {
|
|
for _, email := range l.Emails {
|
|
email.SetOption(context.Background(), opt...)
|
|
}
|
|
}
|
|
|
|
func (l *DefaultEmailFactory) GetEmail(emailType EmailType) (EmailInterface, error) {
|
|
email, ok := l.Emails[emailType]
|
|
if !ok {
|
|
return nil, errors.New("not implemented")
|
|
}
|
|
return email, nil
|
|
}
|
|
|
|
func (l *DefaultEmailFactory) UnRegister(emailType EmailType) {
|
|
delete(l.Emails, emailType)
|
|
}
|