-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
94 lines (74 loc) · 1.54 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
92
93
94
package main
import (
"fmt"
"io"
"log"
"net/http"
"time"
"github.com/maxence-charriere/go-app/v10/pkg/app"
)
const (
PORT = ":8003"
DELAY_CHECK_UPDATE = 2
// TODO: change this to see hot reload on web browser
VERSION = "0.1"
)
type hello struct {
app.Compo
lastUpdatedTime string
}
func (h *hello) Render() app.UI {
return app.Div().Body(
app.H1().Text("VERSION: "+VERSION),
app.P().Text("Hello World! 😎"),
)
}
func fetchUpdatedTime() string {
r, err := http.Get("/updated")
if err != nil {
app.Log(err)
return ""
}
defer r.Body.Close()
b, err := io.ReadAll(r.Body)
if err != nil {
app.Log(err)
return ""
}
return string(b)
}
func (h *hello) OnMount(ctx app.Context) {
h.lastUpdatedTime = ""
for {
newUpdatedTime := fetchUpdatedTime()
if h.lastUpdatedTime == "" {
h.lastUpdatedTime = newUpdatedTime
} else if h.lastUpdatedTime != newUpdatedTime {
ctx.Reload()
}
time.Sleep(DELAY_CHECK_UPDATE * time.Second)
}
}
type lastUpdated struct {
timestamp string
}
func (n *lastUpdated) ServeHTTP(w http.ResponseWriter, r *http.Request) {
w.Write([]byte(n.timestamp))
}
func main() {
app.Route("/", func() app.Composer {
return &hello{}
})
app.RunWhenOnBrowser()
http.Handle("/", &app.Handler{
Name: "Hello",
Description: "An Hello World! example",
})
http.Handle("/updated", &lastUpdated{
timestamp: time.Now().Local().UTC().String(),
})
fmt.Println("Running on: http://localhost" + PORT)
if err := http.ListenAndServe(PORT, nil); err != nil {
log.Fatal(err)
}
}