This commit is contained in:
2026-09-21 13:17:57 +10:00
parent a4ffa93a30
commit c62ea1e80a
4 changed files with 129 additions and 0 deletions
+20
View File
@@ -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)
}
}
+3
View File
@@ -0,0 +1,3 @@
module gitea.rantorium.com/Troy/notifyha
go 1.27.1
+98
View File
@@ -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,
})
}
+8
View File
@@ -0,0 +1,8 @@
package notifyha
const (
Info = "info"
Warning = "warning"
Error = "error"
Critical = "critical"
)