-
Notifications
You must be signed in to change notification settings - Fork 2
/
http.go
100 lines (77 loc) · 2.09 KB
/
http.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
92
93
94
95
96
97
98
99
100
package main
import (
"log"
"net/http"
"strconv"
"time"
"github.com/ant0ine/go-json-rest/rest"
"github.com/gorilla/mux"
)
func homeHandler(w http.ResponseWriter, r *http.Request) {
templateFile, err := template("index.html")
if err != nil {
log.Println(err)
http.Error(w, "Template error", http.StatusInternalServerError)
return
}
w.Write(templateFile)
}
func statusHandler(hub *StatusHub) func(rest.ResponseWriter, *rest.Request) {
return func(w rest.ResponseWriter, _ *rest.Request) {
currentStatus := hub.Status()
type apiStatus struct {
Status
LastUpdatedAgo string `json:"last_update"`
Restarted string `json:"uptime_p"`
}
byIP := make(map[string]*apiStatus)
for _, st := range currentStatus {
var lastUpdatedAgoStr, uptimeStr string
lastUpdatedAgo := DayDuration{time.Since(st.LastStatusUpdate)}
uptime := DayDuration{time.Since(time.Unix(time.Now().Unix()-st.Uptime, 0))}
if uptime.Seconds() <= lastUpdatedAgo.Seconds() {
uptimeStr = ""
} else {
uptimeStr = uptime.DayString()
}
if lastUpdatedAgo.Seconds() > 1 {
lastUpdatedAgoStr = lastUpdatedAgo.DayString()
} else {
lastUpdatedAgoStr = "now"
}
rv := &apiStatus{
*st,
lastUpdatedAgoStr,
uptimeStr,
}
byIP[st.IP] = rv
}
// remoteIP := req.RemoteAddr
w.WriteJson(map[string]interface{}{"servers": byIP})
}
}
func setupMux(hub *StatusHub) http.Handler {
api := rest.NewApi()
api.Use(rest.DefaultDevStack...)
apirouter, err := rest.MakeRouter(
rest.Get("/status", statusHandler(hub)),
)
if err != nil {
log.Fatal(err)
}
api.SetApp(apirouter)
router := mux.NewRouter()
router.HandleFunc("/", homeHandler)
router.PathPrefix("/api/").Handler(http.StripPrefix("/api", api.MakeHandler()))
router.PathPrefix("/static/").HandlerFunc(serveStatic)
smux := http.NewServeMux()
smux.Handle("/", router)
return smux
}
func startHTTP(port int, hub *StatusHub) {
h := setupMux(hub)
listen := ":" + strconv.Itoa(port)
log.Println("Going to listen on port", listen)
// handlers.CombinedLoggingHandler(os.Stdout,
http.ListenAndServe(listen, h)
}