errorhandler/main.go
Thies Mueller 3943edd52a
Some checks failed
Build Go Project / build (push) Failing after 1m31s
initial commit
2024-11-04 16:50:20 +01:00

117 lines
3.4 KiB
Go

package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"strings"
"time"
)
type Config struct {
NtfyServer string `json:"ntfy_server"`
AccessToken string `json:"access_token"`
Channel string `json:"channel"`
}
type ErrorLog struct {
Script string `json:"script"`
Log string `json:"log"`
}
func loadConfig(filename string) (Config, error) {
var config Config
data, err := ioutil.ReadFile(filename)
if err != nil {
return config, err
}
err = json.Unmarshal(data, &config)
return config, err
}
func sendNotification(config Config, message string, title string, priority string) {
req, err := http.NewRequest("POST", fmt.Sprintf("%s/%s", config.NtfyServer, config.Channel), nil)
if err != nil {
log.Println("Failed to create request:", err)
return
}
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", config.AccessToken))
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Title", title)
req.Header.Set("Priority", priority)
req.Body = ioutil.NopCloser(strings.NewReader(message))
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
log.Println("Failed to send notification:", err)
return
}
defer resp.Body.Close()
log.Println("Notification sent. Status code:", resp.StatusCode)
}
func errorHandler(w http.ResponseWriter, r *http.Request) {
// Notify that the error handler has started
timestamp := time.Now().Format(time.RFC3339)
config, err := loadConfig("config.json")
if err == nil {
startMessage := fmt.Sprintf("Error handler started at %s", timestamp)
sendNotification(config, startMessage, "Error Handler Notification", "high")
} else {
log.Println("Failed to load config for startup notification:", err)
}
if r.Method != http.MethodPost {
http.Error(w, "Only POST method is allowed", http.StatusMethodNotAllowed)
return
}
var errorLog ErrorLog
err = json.NewDecoder(r.Body).Decode(&errorLog)
if err != nil {
http.Error(w, "Invalid JSON", http.StatusBadRequest)
return
}
sendNotification(config, fmt.Sprintf("Error in Script: **%s**\n\nLog:\n```\n%s\n```", errorLog.Script, errorLog.Log), "Error Notification", "high")
w.WriteHeader(http.StatusOK)
fmt.Fprintf(w, "Notification sent for script: %s", errorLog.Script)
}
func successHandler(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "Only POST method is allowed", http.StatusMethodNotAllowed)
return
}
timestamp := time.Now().Format(time.RFC3339)
config, err := loadConfig("config.json")
if err != nil {
log.Println("Failed to load config:", err)
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
return
}
message := fmt.Sprintf("Script ran successfully at %s", timestamp)
sendNotification(config, message, "Success Notification", "low")
w.WriteHeader(http.StatusOK)
fmt.Fprintf(w, "Success notification sent.")
}
func main() {
http.HandleFunc("/errorlog", errorHandler)
http.HandleFunc("/success", successHandler)
log.Println("Starting server on :2342...")
err := http.ListenAndServe(":2342", nil)
if err != nil {
log.Fatal("Server failed:", err)
}
}