status/main.go
2023-10-01 10:34:12 +07:00

102 lines
2.1 KiB
Go

package main
import (
"log"
"net"
"net/http"
"os"
"git.exozy.me/exozyme/status/scanner"
"github.com/cbroglie/mustache"
)
func parseAndRenderTemplate(templateLocation string, data interface{}) (string, error) {
tmpl, err := mustache.ParseFile(templateLocation)
if err != nil {
log.Println("Failed to parse template:", err)
return "", err
}
res, err := tmpl.Render(data)
if err != nil {
log.Println("Failed to render template:", err)
return "", err
}
return res, nil
}
var config scanner.Config = scanner.LoadTOMLConfig()
func rootPage(w http.ResponseWriter, r *http.Request) {
if r.Method != "GET" {
return
}
// get service status'
var data []scanner.ServiceStatus
for _, v := range config.Service {
data = append(data, scanner.TestService(v))
}
log.Printf("%v", data)
parsedTemplate, err := parseAndRenderTemplate("templates/index.html", data)
if err != nil {
http.Error(w, err.Error(), 500)
}
w.Write([]byte(parsedTemplate))
}
func removeFile(path string) {
err := os.Remove(path)
if err != nil && !os.IsNotExist(err) {
log.Fatal(err)
}
}
func main() {
http.HandleFunc("/", rootPage)
fs := http.FileServer(http.Dir("./public"))
http.Handle("/public/", http.StripPrefix("/public/", fs))
protocol := "tcp"
addr := "localhost:3333"
var unix_socket_path string
var is_unix bool
if config.UnixSocket != "" {
// get unix socket path from the config else
unix_socket_path = config.UnixSocket
is_unix = true
} else {
// fallback
unix_socket_path, is_unix = os.LookupEnv("PORT")
}
if is_unix {
protocol = "unix"
addr = unix_socket_path
// VnPower: is this unsafe?
removeFile(addr) // ideally this should be run at program exit. sadly Go's defer doesn't care about signals or panic
}
srv := &http.Server{Addr: addr, Handler: nil}
ln, err := net.Listen(protocol, addr)
if err != nil {
log.Fatal(err)
}
if is_unix {
err = os.Chmod(addr, 0660)
if err != nil {
log.Fatal(err)
}
log.Printf("Listening on %v\n", addr)
} else {
log.Printf("Listening on http://%v/\n", addr)
}
log.Fatal(srv.Serve(ln))
}