-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
46 lines (37 loc) · 789 Bytes
/
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
package main
import (
"encoding/json"
"net/http"
"time"
"github.com/shirou/gopsutil/cpu"
"github.com/shirou/gopsutil/mem"
"golang.org/x/net/websocket"
)
type stats struct {
Memory float64 `json:"memory"`
CPU []float64 `json:"cpu"`
}
func (s *stats) getCPU() {
s.CPU, _ = cpu.Percent(time.Second, true)
}
func (s *stats) getMemory() {
v, _ := mem.VirtualMemory()
s.Memory = v.UsedPercent
}
func (s stats) toJSON() []byte {
jsonStr, _ := json.Marshal(s)
return jsonStr
}
func statsHandler(ws *websocket.Conn) {
for {
s := new(stats)
s.getCPU()
s.getMemory()
_, _ = ws.Write(s.toJSON())
}
}
func main() {
http.Handle("/stats", websocket.Handler(statsHandler))
http.Handle("/", http.FileServer(http.Dir("./static")))
http.ListenAndServe(":8080", nil)
}