-
Notifications
You must be signed in to change notification settings - Fork 0
/
web_interface.cr
69 lines (54 loc) · 1.22 KB
/
web_interface.cr
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
require "kemal"
require "fswatch"
require "mosquito"
class SocketBroadcaster
@outputs = [] of HTTP::WebSocket
delegate size, to: @outputs
def initialize
end
def broadcast(message)
@outputs.each do |output|
output.send message
end
end
def register(output : HTTP::WebSocket)
@outputs << output
output.on_close { @outputs.delete output }
end
end
class EventStream < SocketBroadcaster
def register(output : HTTP::WebSocket)
super
output.on_message do |message|
output.send "pong" if message == "ping"
end
end
end
get "/" do
File.read("public/index.html")
end
hot_reload = SocketBroadcaster.new
FSWatch.watch "." do |event|
hot_reload.broadcast("hot reload")
end
ws "/hot-reload" do |socket|
hot_reload.register socket
end
event_stream = Mosquito::Inspector.event_receiver
event_stream_clients = EventStream.new
def message_formatter(message : Mosquito::Backend::BroadcastMessage) : String
{
:channel => message.channel,
:message => message.message
}.to_json
end
spawn do
loop do
message = event_stream.receive
event_stream_clients.broadcast message_formatter(message)
end
end
ws "/events" do |socket|
event_stream_clients.register socket
end
Kemal.run