powerpaneld/main.go

98 lines
2.1 KiB
Go
Raw Normal View History

2024-10-06 09:48:35 -05:00
package main
import (
"fmt"
"net/http"
"strings"
"time"
"go.wit.com/log"
"go.wit.com/lib/gui/shell"
2024-10-06 09:48:35 -05:00
)
// var accessf, clientf *os.File
2024-10-06 09:48:35 -05:00
// var repoMap map[string]string
// var versionMap map[string]string
// var keysSorted []string
2024-10-06 09:48:35 -05:00
// remove '?' part and trailing '/'
func cleanURL(url string) string {
url = "/" + strings.Trim(url, "/")
return url
}
func okHandler(w http.ResponseWriter, r *http.Request) {
var tmp string
tmp = cleanURL(r.URL.Path)
parts := strings.Split(tmp, "?")
log.Warn("URL =", tmp)
log.Info("client sent url =", tmp)
log.Info("parts are:", parts)
// requrl := parts[0]
if tmp == "/powersource" {
fmt.Fprintln(w, "TODO: fix this")
2024-10-06 09:48:35 -05:00
return
}
if tmp == "/lastoutage" {
// r := shell.Output("", []string{"ls", "-l", "/"})
2024-11-08 06:44:56 -06:00
r := shell.Run([]string{"pwrstat", "-status"})
// log.Info("ls -l / START")
// log.Info("ls -l / =", r.Stdout())
// log.Info("ls -l / END")
2024-11-08 06:44:56 -06:00
output := strings.Join(r.Stdout, "\n")
fmt.Fprintln(w, output)
return
}
fmt.Fprintln(w, "UNKNOWN URL:", tmp)
2024-10-06 09:48:35 -05:00
// log.Warn("BAD URL =", url, "REPO URL =", repourl)
// badurl(w, r.URL.String())
// fmt.Fprintln(w, "BAD", tmp)
}
func main() {
var hostname string = args.Hostname
if hostname == "" {
hostname = "localhost"
}
log.Info("curl http://" + hostname + ":3000/powersource # shows if your power grid is up")
log.Info("curl http://" + hostname + ":3000/lastoutage # shows the last time your power grid went down")
log.Info("hostname =", hostname)
2024-10-06 09:48:35 -05:00
http.HandleFunc("/", okHandler)
err := http.ListenAndServe(":3000", nil)
if err != nil {
log.Println("Error starting server:", err)
}
}
func formatDuration(d time.Duration) string {
seconds := int(d.Seconds()) % 60
minutes := int(d.Minutes()) % 60
hours := int(d.Hours()) % 24
days := int(d.Hours()) / 24
result := ""
if days > 0 {
result += fmt.Sprintf("%dd ", days)
return result
}
if hours > 0 {
result += fmt.Sprintf("%dh ", hours)
return result
}
if minutes > 0 {
result += fmt.Sprintf("%dm ", minutes)
return result
}
if seconds > 0 {
result += fmt.Sprintf("%ds", seconds)
}
return result
}