2021-02-03 16:40:06 +03:00
|
|
|
module main
|
|
|
|
|
2021-03-02 22:30:18 +03:00
|
|
|
import os
|
2021-02-03 16:40:06 +03:00
|
|
|
import rand
|
|
|
|
import time
|
|
|
|
import vweb
|
|
|
|
import vweb.sse
|
|
|
|
|
|
|
|
struct App {
|
|
|
|
vweb.Context
|
|
|
|
}
|
|
|
|
|
|
|
|
fn main() {
|
2021-08-03 16:03:16 +03:00
|
|
|
mut app := &App{}
|
2021-05-22 07:02:21 +03:00
|
|
|
app.serve_static('/favicon.ico', 'favicon.ico')
|
2021-03-02 22:30:18 +03:00
|
|
|
app.mount_static_folder_at(os.resource_abs_path('.'), '/')
|
2021-08-03 16:03:16 +03:00
|
|
|
vweb.run(app, 8081)
|
2021-02-03 16:40:06 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
pub fn (mut app App) index() vweb.Result {
|
|
|
|
title := 'SSE Example'
|
|
|
|
return $vweb.html()
|
|
|
|
}
|
|
|
|
|
|
|
|
fn (mut app App) sse() vweb.Result {
|
|
|
|
mut session := sse.new_connection(app.conn)
|
2022-03-06 20:01:22 +03:00
|
|
|
// Note: you can setup session.write_timeout and session.headers here
|
2021-02-03 16:40:06 +03:00
|
|
|
session.start() or { return app.server_error(501) }
|
|
|
|
session.send_message(data: 'ok') or { return app.server_error(501) }
|
|
|
|
for {
|
|
|
|
data := '{"time": "$time.now().str()", "random_id": "$rand.ulid()"}'
|
|
|
|
session.send_message(event: 'ping', data: data) or { return app.server_error(501) }
|
|
|
|
println('> sent event: $data')
|
2021-02-27 20:41:06 +03:00
|
|
|
time.sleep(1 * time.second)
|
2021-02-03 16:40:06 +03:00
|
|
|
}
|
|
|
|
return app.server_error(501)
|
|
|
|
}
|