-
Notifications
You must be signed in to change notification settings - Fork 12
/
web.rb
67 lines (57 loc) · 1.38 KB
/
web.rb
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
require 'goliath'
require 'redis'
require 'json'
require 'rack/utils'
module Options
def self.redis
options = {driver: :synchrony}
if ENV['REDISTOGO_URL']
uri = URI.parse(ENV['REDISTOGO_URL'])
options.merge!({host: uri.host, port: uri.port, password: uri.password})
end
options
end
end
class Subscribe < Goliath::API
def response(env)
EM.synchrony do
@redis = Redis.new(Options::redis)
channel = env["REQUEST_PATH"].sub(/^\/subscribe\//, '')
@redis.subscribe(channel) do |on|
on.message do |channel, message|
@message = message
env.stream_send(payload)
end
end
end
streaming_response(200, { 'Content-Type' => "text/event-stream" })
end
def on_close(env)
@redis.disconnect
end
def payload
"id: #{Time.now}\n" +
"data: #{@message}" +
"\r\n\n"
end
end
class Receive < Goliath::API
@@redis = Redis.new(Options::redis)
def response(env)
channel = env["REQUEST_PATH"][1..-1]
message = Rack::Utils.escape_html(params["message"])
@@redis.publish(channel, {sender: params["sender"], message: message}.to_json)
[ 200, { }, [ ] ]
end
end
class Server < Goliath::API
map "/" do
run Rack::File.new(File.join(File.dirname(__FILE__), 'public', 'index.html'))
end
map /^\/subscribe.*/ do
run Subscribe.new
end
map /.*/ do
run Receive.new
end
end