package main
import (
"context"
"log"
"net/http"
"strings"
"time"
)
type Notifier struct {
url string
token string
client *http.Client
}
func NewNotifier(url, token string) *Notifier {
return &Notifier{url: strings.TrimRight(url, "/"), token: token, client: &http.Client{Timeout: 10 * time.Second}}
}
func (n *Notifier) Enabled() bool { return n != nil && n.url != "" }
type Notification struct {
Title, Message, Click, Tags string
Priority string
}
func (n *Notifier) Send(topic string, m Notification) {
if !n.Enabled() {
return
}
go func() {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
req, err := http.NewRequestWithContext(ctx, http.MethodPost, n.url+"/"+topic, strings.NewReader(m.Message))
if err != nil {
log.Printf("ntfy: %v", err)
return
}
if n.token != "" {
req.Header.Set("Authorization", "Bearer "+n.token)
}
for k, v := range map[string]string{"Title": m.Title, "Click": m.Click, "Tags": m.Tags, "Priority": m.Priority} {
if v != "" {
req.Header.Set(k, v)
}
}
resp, err := n.client.Do(req)
if err != nil {
log.Printf("ntfy: %v", err)
return
}
resp.Body.Close()
if resp.StatusCode >= 300 {
log.Printf("ntfy: publishing to %s: HTTP %d", topic, resp.StatusCode)
}
}()
}