This commit is contained in:
mkelcik
2023-05-04 17:28:25 +02:00
parent ffd5253f59
commit f911b9ff16
4 changed files with 41 additions and 86 deletions

View File

@@ -3,12 +3,18 @@ package notifications
import (
"context"
"errors"
"fmt"
"log"
"net"
"net/http"
"strings"
"time"
)
const (
configDelimiter = "@"
)
type Notifiers []Notifier
func (n Notifiers) NotifyWithLog(ctx context.Context, notification Notification) error {
@@ -16,6 +22,7 @@ func (n Notifiers) NotifyWithLog(ctx context.Context, notification Notification)
for _, notifier := range n {
if err := notifier.Notify(ctx, notification); err != nil {
outErr = errors.Join(outErr, err)
continue
}
log.Printf("Notification sent via %s\n", notifier.Tag())
}
@@ -30,9 +37,19 @@ type Notification struct {
Domain string `json:"domain"`
}
var Available = map[string]func() (Notifier, error){
webhookTag: func() (Notifier, error) {
return NewWebhookNotification(NewWebhookConfigFromEnv(), &http.Client{
func (n Notification) ToSlice() []string {
return []string{n.OldIp.String(), n.NewIp.String(), n.CheckedAt.Format(time.RFC3339), n.ResolverTag, n.Domain}
}
var Available = map[string]func(string) (Notifier, error){
webhookTag: func(config string) (Notifier, error) {
parts := strings.Split(config, configDelimiter)
if len(parts) < 2 {
return nil, fmt.Errorf("wrong webhook config, missing url part")
}
return NewWebhookNotification(WebhookConfig{Url: parts[1]}, &http.Client{
Timeout: 10 * time.Second,
}), nil
},
@@ -42,3 +59,18 @@ type Notifier interface {
Tag() string
Notify(ctx context.Context, notification Notification) error
}
func GetNotifiers(tags []string) Notifiers {
out := Notifiers{}
for _, t := range tags {
if initFn, ok := Available[strings.Split(t, configDelimiter)[0]]; ok {
notifier, err := initFn(t)
if err != nil {
log.Println(err)
continue
}
out = append(out, notifier)
}
}
return out
}