http-server-status/main.go

86 lines
1.9 KiB
Go
Raw Normal View History

2021-09-20 09:28:00 +00:00
package main
import (
2021-09-20 13:45:01 +00:00
_ "embed"
2021-09-20 09:28:00 +00:00
"encoding/json"
"github.com/rs/zerolog/log"
checks "http-server-status/internal/pkg/checks"
"net/http"
"sync"
)
2021-09-20 13:45:01 +00:00
//go:embed template/index.html
var s string
2021-09-20 09:28:00 +00:00
var checkList []checks.Check
func init() {
2021-09-20 10:38:41 +00:00
readConfig()
log.Debug().Int("max_percent", c.Checks.HDD.MaxPercent).Msg("HDD CHECK")
checkList = append(checkList, checks.HDD{c.Checks.HDD}, checks.Memory{Config: c.Checks.Memory}, checks.Load{Config: c.Checks.Load})
2021-09-20 09:28:00 +00:00
}
func main() {
http.HandleFunc("/", func(writer http.ResponseWriter, request *http.Request) {
2021-09-20 21:28:24 +00:00
_, gloableRes := checkSystem()
2021-09-20 21:52:07 +00:00
if gloableRes == false {
writer.WriteHeader(http.StatusInternalServerError)
2021-09-20 21:28:24 +00:00
}
2021-09-20 21:52:07 +00:00
writer.Write([]byte(s))
})
http.HandleFunc("/data.json", handler)
2021-09-20 10:38:41 +00:00
err := http.ListenAndServe(c.HTTP.Listen, nil)
2021-09-20 09:28:00 +00:00
log.Fatal().Err(err).Msg("Shutdown")
}
func handler(w http.ResponseWriter, r *http.Request) {
res, gloableRes := checkSystem()
2021-09-20 10:38:41 +00:00
httpResposne := struct {
Checks map[string]ResultReturn
2021-09-20 10:38:41 +00:00
Config Config
}{Checks: res, Config: c}
resJson, err := json.Marshal(httpResposne)
2021-09-20 09:28:00 +00:00
if err != nil {
2021-09-20 21:14:52 +00:00
log.Fatal().Err(err).Interface("httpResponse", ResultReturn{}).Msg("Check Error")
2021-09-20 09:28:00 +00:00
}
if gloableRes {
w.Write(resJson)
return
}
http.Error(w, string(resJson), http.StatusInternalServerError)
}
2021-09-20 13:45:01 +00:00
type ResultReturn struct {
Success bool `json:"success"`
Data interface{} `json:"data"`
}
func checkSystem() (map[string]ResultReturn, bool) {
2021-09-20 09:28:00 +00:00
globaleResult := true
wg := sync.WaitGroup{}
res := make(map[string]ResultReturn)
2021-09-20 09:28:00 +00:00
for _, c := range checkList {
wg.Add(1)
go func(check checks.Check) {
defer wg.Done()
s, data, _ := check.Execute()
2021-09-20 21:12:07 +00:00
log.Debug().Str("check", check.Name()).Bool("status", s).Interface("Data", data).Msg("Executed Check, got Results")
2021-09-20 09:28:00 +00:00
if s == false {
globaleResult = false
}
res[check.Name()] = ResultReturn{
Success: s,
Data: data,
}
2021-09-20 09:28:00 +00:00
}(c)
}
wg.Wait()
return res, globaleResult
}