-
Notifications
You must be signed in to change notification settings - Fork 0
/
web.go
96 lines (79 loc) · 2.09 KB
/
web.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
package main
import (
"embed"
"html/template"
"io/fs"
"log"
"net/http"
"os"
"os/signal"
"syscall"
)
//go:embed www
var www embed.FS
type context struct {
conf *config
webServer *http.Server
interrupt chan bool
layout *template.Template
}
type PageContext struct {
c *context
Name string
Version string
WidgetLayout [][]string
}
func (p *PageContext) UrlFor(path string) string {
if p.c.conf.getAppUrl() == "" {
return path
}
return p.c.conf.getAppUrl() + "/" + path
}
func newContext(conf *config) *context {
result := &context{conf: conf, interrupt: make(chan bool)}
tpl, err := template.ParseFS(www, "www/template.html")
if err != nil {
log.Fatal(err)
}
result.layout = tpl
return result
}
func (c *context) runWebServer() {
mux := http.NewServeMux()
serverRoot, _ := fs.Sub(www, "www")
mux.Handle("/static/", http.FileServer(http.FS(serverRoot)))
mux.HandleFunc("/sysinfo.json", initRestContext(c.conf).HandleSysinfoData)
mux.HandleFunc("/", c.handleIndex)
c.webServer = &http.Server{Handler: mux, Addr: c.conf.getServerUri()}
log.Print("-- sysinfo started on ", c.conf.getServerUri())
if err := c.webServer.ListenAndServe(); err != nil && err != http.ErrServerClosed {
log.Print("-- sysinfo start failed: ", err)
c.interrupt <- true
} else {
log.Print("-- sysinfo finished")
}
}
func (c *context) handleStop() {
ch := make(chan os.Signal, 1)
signal.Notify(ch, os.Interrupt, syscall.SIGHUP, syscall.SIGINT, syscall.SIGQUIT, syscall.SIGTERM)
select {
case <-ch:
case <-c.interrupt:
}
log.Print("-- stopping sysinfo")
if c.webServer != nil {
c.webServer.Close()
}
}
func (c *context) handleIndex(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "" || r.URL.Path == "/" || r.URL.Path == "index.html" {
p := &PageContext{c: c, Name: c.conf.name, Version: c.conf.getVersion(), WidgetLayout: c.conf.widgets}
w.Header().Set("content-type", "text/html")
if err := c.layout.Execute(w, p); err != nil {
w.WriteHeader(http.StatusInternalServerError)
log.Println(err)
}
} else {
w.WriteHeader(http.StatusNotFound)
}
}