-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
86 lines (74 loc) · 1.78 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
package main
import (
"encoding/json"
"fmt"
"html/template"
"log"
"net/http"
"os"
"github.com/shirou/gopsutil/cpu"
"github.com/shirou/gopsutil/mem"
)
type UtilizationPercent struct {
CPUpercent float64
MemPercent float64
}
func getCPUUsage() (float64, error) {
cpuPercent, err := cpu.Percent(0, false)
if err != nil {
return 0, err
}
return cpuPercent[0], nil
}
func getMemoryUsage() (float64, error) {
v, err := mem.VirtualMemory()
if err != nil {
return 0, err
}
return float64(v.Used) / float64(v.Total) * 100, nil
}
func handler(w http.ResponseWriter, r *http.Request) {
t, err := template.ParseFiles("./templates/index.html")
if err != nil {
log.Fatal(err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// os.Setenv("POD_NAME", "TESTING")
err = t.Execute(w, os.Getenv("POD_NAME"))
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
func apiResponse(w http.ResponseWriter, r *http.Request) {
cpuPercent, err := getCPUUsage()
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
memUsedPercent, err := getMemoryUsage()
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
data := map[string]float64{
"CPUPercent": cpuPercent,
"MemoryUsage": memUsedPercent,
}
jsonData, err := json.Marshal(data)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
w.Write(jsonData)
}
func main() {
fs := http.FileServer(http.Dir("static"))
http.Handle("/static/", http.StripPrefix("/static/", fs))
http.HandleFunc("/", handler)
http.HandleFunc("/data", apiResponse)
fmt.Println("Server listening on port 8080")
http.ListenAndServe(":8080", nil)
}