go-uptime-alert/main.go

82 lines
1.4 KiB
Go
Raw Normal View History

2023-10-25 10:23:36 +02:00
package main
import (
"encoding/json"
"log"
"net/http"
"os"
"time"
)
var (
configFile string = os.Getenv("HOME") + "/.config/go-uptime-alert.json"
)
type Config struct {
ServiceUrlUuids []struct {
SiteURL string `json:"site_url"`
HealthChecksPingURL string `json:"hc_ping_url"`
} `json:"service_urls_uuids"`
}
func getConfig(configFile string) (*Config, error) {
data, err := os.ReadFile(configFile)
if err != nil {
return nil, err
}
config := &Config{}
if err := json.Unmarshal(data, config); err != nil {
return nil, err
}
return config, err
}
func checkURL(url string) (int, error) {
resp, err := http.Get(url)
if err != nil {
return 0, err
}
defer resp.Body.Close()
return resp.StatusCode, nil
}
func sendPingToHC(hcPingURL string) error {
client := &http.Client{
Timeout: 10 * time.Second,
}
_, err := client.Head(hcPingURL)
if err != nil {
return err
}
return nil
}
func main() {
config, err := getConfig(configFile)
if err != nil {
log.Fatalln("Error getting config located at " + configFile)
}
for _, v := range config.ServiceUrlUuids {
statusCode, err := checkURL(v.SiteURL)
if err != nil {
log.Fatalln(err)
}
if statusCode == http.StatusOK {
if err := sendPingToHC(v.HealthChecksPingURL); err != nil {
log.Printf("%s\n", err)
} else {
log.Printf("%s: OK\n", v.SiteURL)
}
} else {
log.Printf("%s: DOWN\n", v.SiteURL)
}
}
}