81 lines
1.7 KiB
Go
81 lines
1.7 KiB
Go
|
|
package main
|
|
|
|
import (
|
|
"bytes"
|
|
"encoding/json"
|
|
"fmt"
|
|
"log"
|
|
"net/http"
|
|
"os"
|
|
)
|
|
|
|
// Notification payload
|
|
type Notification struct {
|
|
Title string `json:"title"`
|
|
Message string `json:"message"`
|
|
}
|
|
|
|
func main() {
|
|
http.HandleFunc("/notify", notifyHandler)
|
|
log.Println("Starting server on :8080...")
|
|
log.Fatal(http.ListenAndServe(":8080", nil))
|
|
}
|
|
|
|
func notifyHandler(w http.ResponseWriter, r *http.Request) {
|
|
if r.Method != http.MethodPost {
|
|
w.WriteHeader(http.StatusMethodNotAllowed)
|
|
w.Write([]byte("Method not allowed"))
|
|
return
|
|
}
|
|
|
|
var notif Notification
|
|
if err := json.NewDecoder(r.Body).Decode(¬if); err != nil {
|
|
w.WriteHeader(http.StatusBadRequest)
|
|
w.Write([]byte("Invalid payload"))
|
|
return
|
|
}
|
|
|
|
// Call Discord notification function
|
|
if err := sendDiscordNotification(notif.Title, notif.Message); err != nil {
|
|
w.WriteHeader(http.StatusInternalServerError)
|
|
w.Write([]byte("Failed to send Discord notification"))
|
|
return
|
|
}
|
|
|
|
w.WriteHeader(http.StatusOK)
|
|
w.Write([]byte("Notification sent"))
|
|
}
|
|
|
|
func sendDiscordNotification(title, message string) error {
|
|
webhookURL := os.Getenv("WEBHOOK_URL")
|
|
if webhookURL == "" {
|
|
return fmt.Errorf("WEBHOOK_URL environment variable not set")
|
|
}
|
|
|
|
// Discord webhook payload
|
|
type discordPayload struct {
|
|
Content string `json:"content"`
|
|
}
|
|
|
|
content := "**" + title + "**\n" + message
|
|
payload := discordPayload{Content: content}
|
|
|
|
jsonData, err := json.Marshal(payload)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
resp, err := http.Post(webhookURL, "application/json", bytes.NewBuffer(jsonData))
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer resp.Body.Close()
|
|
|
|
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
|
|
return fmt.Errorf("Discord webhook returned status: %s", resp.Status)
|
|
}
|
|
|
|
return nil
|
|
}
|