2021-02-03 14:40:06 +01:00
|
|
|
module main
|
|
|
|
|
|
|
|
import rand
|
|
|
|
import time
|
|
|
|
import vweb
|
|
|
|
import vweb.sse
|
|
|
|
|
|
|
|
struct App {
|
|
|
|
vweb.Context
|
|
|
|
}
|
|
|
|
|
|
|
|
fn main() {
|
|
|
|
vweb.run<App>(8081)
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn (mut app App) init_once() {
|
|
|
|
app.serve_static('/favicon.ico', 'favicon.ico', 'img/x-icon')
|
2021-02-21 19:01:29 +01:00
|
|
|
app.handle_static('.', false)
|
2021-02-03 14:40:06 +01: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)
|
|
|
|
// NB: you can setup session.write_timeout and session.headers here
|
|
|
|
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 18:41:06 +01:00
|
|
|
time.sleep(1 * time.second)
|
2021-02-03 14:40:06 +01:00
|
|
|
}
|
|
|
|
return app.server_error(501)
|
|
|
|
}
|