-
Notifications
You must be signed in to change notification settings - Fork 2
/
live.v
84 lines (68 loc) · 1.31 KB
/
live.v
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
module main
import vweb
import x.websocket
struct App {
vweb.Context
pub mut:
model Model
}
fn main() {
vweb.run<App>(8082)
}
pub fn (mut app App) index() vweb.Result {
return $vweb.html()
}
pub fn (mut app App) init() {
app.model = &Model{
count: 3
}
}
pub fn (mut app App) init_once() {
go start_server(mut app)
}
struct Model {
mut:
count int
}
fn start_server(mut app App) ? {
mut s := websocket.new_server(30000, '')
s.ping_interval = 100
s.on_connect(fn (mut s websocket.ServerClient) ?bool {
if s.resource_name != '/' {
panic('unexpected resource name in test')
return false
}
return true
}) ?
s.on_message_ref(fn (mut ws websocket.Client, msg &websocket.Message, mut model Model) ? {
event := msg.payload.bytestr()
update(event, mut model)
rendered := view(model)
ws.write(rendered.bytes(), msg.opcode) or { panic(err) }
}, app.model)
s.on_close(fn (mut ws websocket.Client, code int, reason string) ? {
// not used
})
s.listen() or {}
}
fn update(event string, mut model Model) {
match event {
'init' {
model.count = 0
}
'inc' {
model.count = model.count + 1
}
'dec' {
model.count = model.count - 1
}
else {}
}
}
fn view(model Model) string {
return '
<div>$model.count</div>
<button v-click="inc">+</button>
<button v-click="dec">-</button>
'
}