-
Notifications
You must be signed in to change notification settings - Fork 21
/
main.go
76 lines (63 loc) · 1.48 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
package main
import (
"html/template"
"log"
"net/http"
"time"
"github.com/gorilla/mux"
)
func calcUpdateDuration() time.Duration {
if StartTime.IsZero() {
return 0
}
return time.Since(StartTime)
}
type ExampleRouter struct {
*mux.Router
tmpl *template.Template
updateDuration time.Duration
}
func NewExampleRouter() (*ExampleRouter, error) {
r := mux.NewRouter()
tmpl, err := template.ParseGlob("./web/templates/*.tmpl")
if err != nil {
return nil, err
}
updateDuration := calcUpdateDuration()
router := &ExampleRouter{
Router: r,
tmpl: tmpl,
updateDuration: updateDuration,
}
fs := http.FileServer(http.Dir("./web"))
r.HandleFunc("/", router.index)
r.PathPrefix("/").Handler(fs)
return router, nil
}
func (r *ExampleRouter) updateTimeDisplay() string {
if r.updateDuration != 0 {
return r.updateDuration.Truncate(100 * time.Millisecond).String()
}
return "N/A"
}
func (r *ExampleRouter) index(w http.ResponseWriter, req *http.Request) {
err := r.tmpl.ExecuteTemplate(w, "index.tmpl", map[string]string{
"Duration": r.updateTimeDisplay(),
})
if err != nil {
log.Printf("index: %v")
}
}
func main() {
router, err := NewExampleRouter()
if err != nil {
log.Fatalf("Router creation failed: %v", err)
}
http.Handle("/", router)
log.Println("Serving on port 8000")
log.Printf("Deploy time: %s\n", router.updateTimeDisplay())
err = http.ListenAndServe(":8000", nil)
if err != nil {
log.Fatalf("Server exited with: %v", err)
}
}