forked from tariqbuilds/linux-dash
-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
91 lines (80 loc) · 2.6 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
87
88
89
90
91
// linux-go-dash project main.go
package main
import (
"bytes"
"encoding/json"
"fmt"
"github.com/protip/linux-go-dash/util/cpu"
"github.com/protip/linux-go-dash/util/mem"
"github.com/protip/linux-go-dash/util/system"
"io/ioutil"
"net/http"
"os"
"strconv"
)
func main() {
http.HandleFunc("/", indexHandler)
http.Handle("/js/", http.StripPrefix("/js/", http.FileServer(http.Dir("js"))))
http.Handle("/css/", http.StripPrefix("/css/", http.FileServer(http.Dir("css"))))
http.HandleFunc("/sh/hostname", hostnameHandler)
http.HandleFunc("/sh/uptime", uptimeHandler)
http.HandleFunc("/sh/mem", memHandler)
http.HandleFunc("/sh/loadavg", loadavgHandler)
http.HandleFunc("/sh/numberofcores", numberOfCoresHandler)
http.ListenAndServe(":8080", nil)
}
func indexHandler(w http.ResponseWriter, r *http.Request) {
indexHtml, err := ioutil.ReadFile("index.html")
if err != nil {
panic(err.Error())
}
w.Write(indexHtml)
}
func hostnameHandler(w http.ResponseWriter, r *http.Request) {
hostname, _ := os.Hostname()
var buffer bytes.Buffer
buffer.WriteString(`"`)
buffer.WriteString(hostname)
buffer.WriteString(`\n"`)
w.Write(buffer.Bytes())
}
func uptimeHandler(w http.ResponseWriter, r *http.Request) {
upTime := system.GetUpTime()
response := fmt.Sprint(upTime.UpTime)
enc := json.NewEncoder(w)
enc.Encode(response)
}
func memHandler(w http.ResponseWriter, r *http.Request) {
defer r.Body.Close()
total := mem.GetMB(mem.MemTotal)
used := mem.GetUsedMB()
free := mem.GetFreeMB()
var response = map[string]string{
"Total": strconv.Itoa(total),
"Used": strconv.Itoa(used),
"Free": strconv.Itoa(free),
}
enc := json.NewEncoder(w)
enc.Encode(response)
//w.WriteHeader(200)
}
func loadavgHandler(w http.ResponseWriter, r *http.Request) {
enc := json.NewEncoder(w)
loadavg := cpu.LoadAvg()
numCores := cpu.Count()
var response = map[string]string{
"OneMinute": strconv.FormatFloat(float64(loadavg.OneMinute), 'f', 0, 32),
"FiveMinute": strconv.FormatFloat(float64(loadavg.FiveMinute), 'f', 0, 32),
"FifteenMinute": strconv.FormatFloat(float64(loadavg.FifteenMinute), 'f', 0, 32),
"OneMinute%": strconv.FormatFloat(float64(loadavg.OneMinute)*100/float64(numCores), 'f', 0, 32),
"FiveMinute%": strconv.FormatFloat(float64(loadavg.FiveMinute)*100/float64(numCores), 'f', 0, 32),
"FifteenMinute%": strconv.FormatFloat(float64(loadavg.FifteenMinute)*100/float64(numCores), 'f', 0, 32),
}
enc.Encode(response)
}
func numberOfCoresHandler(w http.ResponseWriter, r *http.Request) {
count := cpu.Count()
countString := strconv.Itoa(count)
enc := json.NewEncoder(w)
enc.Encode(countString)
}