-
Notifications
You must be signed in to change notification settings - Fork 27
/
main.go
92 lines (77 loc) · 1.88 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
package main
import (
"context"
"html/template"
"log"
"net/http"
"time"
"github.com/gorilla/sessions"
"github.com/jfyne/live"
)
const (
tick = "tick"
)
type clock struct {
Time time.Time
}
func newClock(s *live.Socket) *clock {
c, ok := s.Assigns().(*clock)
if !ok {
return &clock{
Time: time.Now(),
}
}
return c
}
func (c clock) FormattedTime() string {
return c.Time.Format("15:04:05")
}
func mount(ctx context.Context, h *live.Handler, r *http.Request, s *live.Socket, connected bool) (interface{}, error) {
// Take the socket data and tranform it into our view model if it is
// available.
c := newClock(s)
// If we are mouting the websocket connection, trigger the first tick
// event.
if connected {
go func() {
time.Sleep(1 * time.Second)
h.Self(s, live.Event{T: tick})
}()
}
return c, nil
}
func main() {
cookieStore := sessions.NewCookieStore([]byte("weak-secret"))
cookieStore.Options.HttpOnly = true
cookieStore.Options.Secure = true
cookieStore.Options.SameSite = http.SameSiteStrictMode
t, err := template.ParseFiles("examples/root.html", "examples/clock/view.html")
if err != nil {
log.Fatal(err)
}
h, err := live.NewHandler(t, "session-key", cookieStore)
if err != nil {
log.Fatal(err)
}
// Set the mount function for this handler.
h.Mount = mount
// Server side events.
// tick event updates the clock every second.
h.HandleSelf(tick, func(s *live.Socket, _ map[string]interface{}) (interface{}, error) {
// Get our model
c := newClock(s)
// Update the time.
c.Time = time.Now()
// Send ourselves another tick in a second.
go func(sock *live.Socket) {
time.Sleep(1 * time.Second)
h.Self(sock, live.Event{T: tick})
}(s)
return c, nil
})
// Run the server.
http.Handle("/clock", h)
http.Handle("/live.js", live.Javascript{})
http.Handle("/auto.js.map", live.JavascriptMap{})
http.ListenAndServe(":8080", nil)
}