/
dashboard.go
62 lines (53 loc) · 1.55 KB
/
dashboard.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
package node
import (
"container/list"
"encoding/json"
"fmt"
"github.com/donkeysharp/gocho/assets"
"github.com/donkeysharp/gocho/pkg/config"
"net/http"
"log"
)
func configHandler(conf *config.Config) func(w http.ResponseWriter, r *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
data, err := json.Marshal(conf)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
return
}
w.Header().Add("Content-Type", "application/json")
w.Write(data)
}
}
func nodesHandler(nodeList *list.List) func(http.ResponseWriter, *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
nodes := make([]*NodeInfo, 0)
for el := nodeList.Front(); el != nil; el = el.Next() {
tmp := el.Value.(*NodeInfo)
nodes = append(nodes, tmp)
}
data, err := json.Marshal(nodes)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
return
}
w.Header().Add("Content-Type", "application/json")
w.Write(data)
}
}
func dashboardServe(conf *config.Config, nodeList *list.List) {
dashboardMux := http.NewServeMux()
dashboardMux.Handle("/", http.FileServer(assets.AssetFS()))
dashboardMux.HandleFunc("/api/config", configHandler(conf))
dashboardMux.HandleFunc("/api/nodes", nodesHandler(nodeList))
// We don't want the dashboard to be public
address := "localhost"
if conf.Debug {
address = "0.0.0.0"
}
fmt.Printf("Starting dashboard at %s:%s\n", address, conf.LocalPort)
err := http.ListenAndServe(fmt.Sprintf("%s:%s", address, conf.LocalPort), dashboardMux)
if err != nil {
log.Fatal(err)
}
}