diff --git a/main.go b/main.go index 6544fdc..9d58cf2 100644 --- a/main.go +++ b/main.go @@ -33,6 +33,49 @@ type alert struct { Annotations map[string]interface{} `json:"annotations"` } +type notification struct { + title string + body string + priority string + tags string +} + +func (rcv *receiver) publish(n *notification) error { + client := &http.Client{Timeout: time.Second * 3} + req, err := http.NewRequest(http.MethodPost, rcv.cfg.ntfy.Topic, strings.NewReader(n.body)) + if err != nil { + return err + } + + // Basic auth + if rcv.cfg.ntfy.Password != "" && rcv.cfg.ntfy.User != "" { + auth := base64.StdEncoding.EncodeToString([]byte(fmt.Sprintf("%s:%s", rcv.cfg.ntfy.User, rcv.cfg.ntfy.Password))) + req.Header.Set("Authorization", fmt.Sprintf("Basic %s", auth)) + } + + req.Header.Set("X-Title", n.title) + + if n.priority != "" { + req.Header.Set("X-Priority", n.priority) + } + + if n.tags != "" { + req.Header.Set("X-Tags", n.tags) + } + + resp, err := client.Do(req) + if err != nil { + return err + } + + defer resp.Body.Close() + if resp.StatusCode != http.StatusOK { + return fmt.Errorf("ntfy: received status code %d", resp.StatusCode) + } + + return nil +} + func (rcv *receiver) handleWebhooks(w http.ResponseWriter, r *http.Request) { defer r.Body.Close() @@ -85,20 +128,6 @@ func (rcv *receiver) handleWebhooks(w http.ResponseWriter, r *http.Request) { body += alertBody } - client := &http.Client{Timeout: time.Second * 3} - req, err := http.NewRequest(http.MethodPost, rcv.cfg.ntfy.Topic, strings.NewReader(body)) - if err != nil { - rcv.logger.Error(err) - } - - // Basic auth - if rcv.cfg.ntfy.Password != "" && rcv.cfg.ntfy.User != "" { - auth := base64.StdEncoding.EncodeToString([]byte(fmt.Sprintf("%s:%s", rcv.cfg.ntfy.User, rcv.cfg.ntfy.Password))) - req.Header.Set("Authorization", fmt.Sprintf("Basic %s", auth)) - } - - req.Header.Set("X-Title", title) - var priority string var tags []string for _, labelName := range rcv.cfg.labels.Order { @@ -123,25 +152,13 @@ func (rcv *receiver) handleWebhooks(w http.ResponseWriter, r *http.Request) { } } - if priority != "" { - req.Header.Set("X-Priority", priority) - } - tagString := strings.Join(tags, ",") - if tagString != "" { - req.Header.Set("X-Tags", tagString) - } - resp, err := client.Do(req) + notification := ¬ification{title: title, body: body, priority: priority, tags: tagString} + err := rcv.publish(notification) if err != nil { rcv.logger.Error(err) } - - defer resp.Body.Close() - if resp.StatusCode != http.StatusOK { - rcv.logger.Errorf("ntfy: received status code %d", resp.StatusCode) - return - } } func (rcv *receiver) basicAuthMiddleware(handler http.HandlerFunc) http.HandlerFunc {