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) { log.Printf("Incoming %s request from %s to %s", r.Method, r.RemoteAddr, r.URL.Path) if r.Method != http.MethodPost { log.Printf("Method not allowed: %s", r.Method) w.WriteHeader(http.StatusMethodNotAllowed) w.Write([]byte("Method not allowed")) return } var notif Notification if err := json.NewDecoder(r.Body).Decode(¬if); err != nil { log.Printf("Invalid payload: %v", err) w.WriteHeader(http.StatusBadRequest) w.Write([]byte("Invalid payload")) return } log.Printf("Received notification payload: Title='%s', Message='%s'", notif.Title, notif.Message) // Call Discord notification function if err := sendDiscordNotification(notif.Title, notif.Message); err != nil { log.Printf("Failed to send Discord notification: %v", err) w.WriteHeader(http.StatusInternalServerError) w.Write([]byte("Failed to send Discord notification")) return } log.Printf("Notification sent successfully for Title='%s'", notif.Title) w.WriteHeader(http.StatusOK) w.Write([]byte("Notification sent")) } func sendDiscordNotification(title, message string) error { webhookURL := os.Getenv("WEBHOOK_URL") if webhookURL == "" { log.Printf("WEBHOOK_URL environment variable not set") 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 { log.Printf("Failed to marshal Discord payload: %v", err) return err } log.Printf("Sending Discord notification: Title='%s', Message='%s'", title, message) resp, err := http.Post(webhookURL, "application/json", bytes.NewBuffer(jsonData)) if err != nil { log.Printf("Error posting to Discord webhook: %v", err) return err } defer resp.Body.Close() if resp.StatusCode < 200 || resp.StatusCode >= 300 { log.Printf("Discord webhook returned status: %s", resp.Status) return fmt.Errorf("Discord webhook returned status: %s", resp.Status) } log.Printf("Discord notification sent successfully: Title='%s'", title) return nil }