diff --git a/example/main.go b/example/main.go new file mode 100644 index 0000000..3fbe98d --- /dev/null +++ b/example/main.go @@ -0,0 +1,20 @@ +package main + +import ( + "log" + + "gitea.rantorium.com/Troy/notifyha" +) + +func main() { + client := notifyha.New("https://homeassistant.example.com/api/webhook/central_notifications") + + err := client.Info( + "Test Message", + "Hello from Go", + "example-app", + ) + if err != nil { + log.Fatal(err) + } +} diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..b12d2ff --- /dev/null +++ b/go.mod @@ -0,0 +1,3 @@ +module gitea.rantorium.com/Troy/notifyha + +go 1.27.1 diff --git a/notify.go b/notify.go new file mode 100644 index 0000000..c2d51af --- /dev/null +++ b/notify.go @@ -0,0 +1,98 @@ +package notifyha + +import ( + "bytes" + "encoding/json" + "fmt" + "net/http" + "time" +) + +type Notification struct { + Event string `json:"event"` + Severity string `json:"severity"` + Title string `json:"title"` + Message string `json:"message"` + Source string `json:"source"` + Tags []string `json:"tags,omitempty"` + Timestamp time.Time `json:"timestamp"` +} + +type Client struct { + WebhookURL string + HTTPClient *http.Client +} + +func New(webhookURL string) *Client { + return &Client{ + WebhookURL: webhookURL, + HTTPClient: &http.Client{ + Timeout: 10 * time.Second, + }, + } +} + +func (c *Client) Send(n Notification) error { + n.Timestamp = time.Now().UTC() + body, err := json.Marshal(n) + if err != nil { + return err + } + + resp, err := c.HTTPClient.Post( + c.WebhookURL, + "application/json", + bytes.NewBuffer(body), + ) + if err != nil { + return err + } + + defer resp.Body.Close() + + if resp.StatusCode >= 300 { + return fmt.Errorf("webhook returned %s", resp.Status) + } + + return nil +} + +func (c *Client) Info(title, message, source string) error { + return c.Send(Notification{ + Event: "notification", + Severity: Info, + Title: title, + Message: message, + Source: source, + }) +} + +func (c *Client) Warning(title, message, source string) error { + return c.Send(Notification{ + Event: "notification", + Severity: Warning, + Title: title, + Message: message, + Source: source, + }) +} + +func (c *Client) Error(title, message, source string) error { + return c.Send(Notification{ + Event: "notification", + Severity: Error, + Title: title, + Message: message, + Source: source, + }) +} + +func (c *Client) Critical(title, message, source string) error { + return c.Send(Notification{ + Event: "notification", + Severity: Critical, + Title: title, + Message: message, + Source: source, + }) +} diff --git a/severity.go b/severity.go new file mode 100644 index 0000000..d7fc009 --- /dev/null +++ b/severity.go @@ -0,0 +1,8 @@ +package notifyha + +const ( + Info = "info" + Warning = "warning" + Error = "error" + Critical = "critical" +)