package handlers import ( "embed" "encoding/json" "html/template" "net/http" "processSupervisor/models" ) type HTopHandler struct { Table *models.HtopTable templates *embed.FS } func NewHTopHandler(templates *embed.FS) (*HTopHandler, error) { table, err := models.NewTable() if err != nil { return nil, err } return &HTopHandler{ Table: table, templates: templates, }, 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).ParseFS( h.templates, "templates/htop/table.html", ), ) tmpl.Execute(w, h.Table) return } tmpl := template.Must( template.New("htop.html").Funcs(funcMap).ParseFS( h.templates, "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) }