package service import ( "context" "fmt" "io" "net/http" "strings" "gitea.dwysokinski.me/Kichiyaki/notificationarr/internal/domain" ) type Ntfy struct { client *http.Client url string topic string username string password string } func NewNtfy(client *http.Client, url string, topic string, username string, password string) *Ntfy { return &Ntfy{ client: client, url: url, topic: topic, username: username, password: password, } } func (n *Ntfy) Publish(ctx context.Context, title, message string) error { // initialize request req, err := http.NewRequestWithContext(ctx, http.MethodPost, n.url+"/"+n.topic, strings.NewReader(message)) if err != nil { return fmt.Errorf("http.NewRequestWithContext: %w", err) } // set required headers req.Header.Set("Title", title) if n.username != "" && n.password != "" { req.SetBasicAuth(n.username, n.password) } // send request resp, err := n.client.Do(req) if err != nil { return fmt.Errorf("client.Do: %w", err) } defer func() { _ = resp.Body.Close() }() _, _ = io.Copy(io.Discard, resp.Body) // discard body, as it is not needed if resp.StatusCode != http.StatusOK { return domain.NewError( domain.WithCode(domain.ErrorCodeIO), domain.WithMessagef("ntfy returned unexpected status code: %d", resp.StatusCode), ) } return nil }