v2 / examples / veb / server_sent_events / server.v
46 lines · 39 sloc · 931 bytes · 3f3a7dc57cc717393daf40dc7d75cff0cf189b0f
Raw
1module main
2
3import os
4import rand
5import time
6import veb
7import veb.sse
8
9struct App {
10 veb.StaticHandler
11}
12
13struct Context {
14 veb.Context
15}
16
17fn main() {
18 mut app := &App{}
19 app.serve_static('/favicon.ico', 'favicon.ico')!
20 app.mount_static_folder_at(os.resource_abs_path('.'), '/')!
21 veb.run[App, Context](mut app, 8081)
22}
23
24// XTODO template broken (@)
25pub fn (mut app App) index() veb.Result {
26 title := 'SSE Example'
27 return $veb.html()
28}
29
30fn (mut app App) sse() veb.Result {
31 ctx.takeover_conn()
32 spawn handle_sse_conn(mut ctx)
33 return veb.no_result()
34}
35
36fn handle_sse_conn(mut ctx Context) {
37 mut session := sse.start_connection(mut ctx.Context)
38 session.send_message(data: 'ok') or { return }
39 for {
40 data := '{"time": "${time.now().str()}", "random_id": "${rand.ulid()}"}'
41 session.send_message(event: 'ping', data: data) or { break }
42 println('> sent event: ${data}')
43 time.sleep(1 * time.second)
44 }
45 session.close()
46}
47