Files
tecamino-proccessSupervisor/handlers/htopHandler.go
Adrian Zürcher b9efeb670d
Some checks failed
Build Process Supervisor / build (push) Failing after 1s
first running version
2025-08-05 12:01:59 +02:00

101 lines
1.9 KiB
Go

package handlers
import (
"encoding/json"
"html/template"
"net/http"
"processSupervisor/models"
)
type HTopHandler struct {
Table *models.HtopTable
}
func NewHTopHandler() (*HTopHandler, error) {
table, err := models.NewTable()
if err != nil {
return nil, err
}
return &HTopHandler{
Table: table,
}, nil
}
func (h *HTopHandler) UpdateHTop(w http.ResponseWriter, r *http.Request) {
err := h.Table.UpdateTable()
if err != nil {
http.Error(w, "Failed to get processes", 500)
return
}
h.Table.Sort(r)
funcMap := template.FuncMap{
"div": divide,
}
w.Header().Set("Content-Type", "text/html; charset=utf-8")
// Detect HTMX request via the HX-Request header
if r.Header.Get("HX-Request") == "true" {
tmpl := template.Must(
template.New("table.html").Funcs(funcMap).ParseFiles("templates/htop/table.html"),
)
tmpl.Execute(w, h.Table)
return
}
tmpl := template.Must(
template.New("htop.html").Funcs(funcMap).ParseFiles(
"templates/htop/htop.html",
"templates/htop/table.html",
),
)
tmpl.Execute(w, h.Table)
}
func divide(a any, b any) float64 {
af := toFloat64(a)
bf := toFloat64(b)
if bf == 0 {
return 0
}
return af / bf
}
func toFloat64(v any) float64 {
switch val := v.(type) {
case int:
return float64(val)
case int32:
return float64(val)
case int64:
return float64(val)
case uint64:
return float64(val)
case float32:
return float64(val)
case float64:
return val
default:
return 0
}
}
// GET /taskmanager/usage
func UsageHandler(w http.ResponseWriter, r *http.Request) {
cpu, mem, err := models.GetSystemUsage()
if err != nil {
http.Error(w, "Failed to get usage", 500)
return
}
usage := struct {
CPU float64 `json:"cpu"`
Mem float64 `json:"mem"`
}{
CPU: cpu,
Mem: mem,
}
json.NewEncoder(w).Encode(usage)
}