From 94579d65c4f0eb4deb6e2c365c64109dbb1b2aa3 Mon Sep 17 00:00:00 2001 From: Fu Diwei Date: Sat, 9 Nov 2024 20:29:13 +0800 Subject: [PATCH] refactor: clean code --- internal/notify/notify.go | 16 ------ internal/notify/utils.go | 17 ++++++ .../providers/serverchan/serverchan.go | 55 +++++++++++++++++++ 3 files changed, 72 insertions(+), 16 deletions(-) create mode 100644 internal/notify/utils.go create mode 100644 internal/pkg/core/notifier/providers/serverchan/serverchan.go diff --git a/internal/notify/notify.go b/internal/notify/notify.go index f414b6d4..4189f62b 100644 --- a/internal/notify/notify.go +++ b/internal/notify/notify.go @@ -193,19 +193,3 @@ func getMailNotifier(conf map[string]any) (notifyPackage.Notifier, error) { return rs, nil } - -func getString(conf map[string]any, key string) string { - if _, ok := conf[key]; !ok { - return "" - } - - return conf[key].(string) -} - -func getBool(conf map[string]any, key string) bool { - if _, ok := conf[key]; !ok { - return false - } - - return conf[key].(bool) -} diff --git a/internal/notify/utils.go b/internal/notify/utils.go new file mode 100644 index 00000000..0c04ed15 --- /dev/null +++ b/internal/notify/utils.go @@ -0,0 +1,17 @@ +package notify + +func getString(conf map[string]any, key string) string { + if _, ok := conf[key]; !ok { + return "" + } + + return conf[key].(string) +} + +func getBool(conf map[string]any, key string) bool { + if _, ok := conf[key]; !ok { + return false + } + + return conf[key].(bool) +} diff --git a/internal/pkg/core/notifier/providers/serverchan/serverchan.go b/internal/pkg/core/notifier/providers/serverchan/serverchan.go new file mode 100644 index 00000000..4d87826f --- /dev/null +++ b/internal/pkg/core/notifier/providers/serverchan/serverchan.go @@ -0,0 +1,55 @@ +package email + +import ( + "context" + "errors" + "net/http" + + notifyHttp "github.com/nikoksr/notify/service/http" + + "github.com/usual2970/certimate/internal/pkg/core/notifier" +) + +type ServerChanNotifierConfig struct { + Url string `json:"url"` +} + +type ServerChanNotifier struct { + config *ServerChanNotifierConfig +} + +var _ notifier.Notifier = (*ServerChanNotifier)(nil) + +func New(config *ServerChanNotifierConfig) (*ServerChanNotifier, error) { + if config == nil { + return nil, errors.New("config is nil") + } + + return &ServerChanNotifier{ + config: config, + }, nil +} + +func (n *ServerChanNotifier) Notify(ctx context.Context, subject string, message string) (res *notifier.NotifyResult, err error) { + srv := notifyHttp.New() + + srv.AddReceivers(¬ifyHttp.Webhook{ + URL: n.config.Url, + Header: http.Header{}, + ContentType: "application/json", + Method: http.MethodPost, + BuildPayload: func(subject, message string) (payload any) { + return map[string]string{ + "text": subject, + "desp": message, + } + }, + }) + + err = srv.Send(ctx, subject, message) + if err != nil { + return nil, err + } + + return ¬ifier.NotifyResult{}, nil +}