Skip to content

Instantly share code, notes, and snippets.

@amitpatelx
Created December 3, 2012 10:41
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save amitpatelx/4194139 to your computer and use it in GitHub Desktop.
Save amitpatelx/4194139 to your computer and use it in GitHub Desktop.
Cross domain streaming with Goliath
#!/usr/bin/env ruby
require 'rubygems'
require 'bundler/setup'
require 'goliath'
class RedisPubsub < Goliath::API
use(Rack::Static, :root => Goliath::Application.app_path("public"), :urls => ["/index.html", "/twitter.html", "/favicon.ico", '/stylesheets/', '/javascripts/', '/images/'])
use Goliath::Rack::Params
use Goliath::Rack::Render, 'json'
def response(env)
if env['PATH_INFO'] == "/"
[301, {'Location' => '/index.html'}, nil]
elsif env['PATH_INFO'] == "/tweets"
config['redis_twitter'].on(:message) do |channel, message|
env.stream_send("data:#{message}\n\n")
end
streaming_response(200, {'Content-Type' => 'text/event-stream', 'Access-Control-Allow-Origin' => '*'})
else
config['redis_news'].on(:message) do |channel, message|
env.stream_send("data:#{message}\n\n")
end
streaming_response(200, {'Content-Type' => 'text/event-stream', 'Access-Control-Allow-Origin' => '*'})
end
end
end
<!-- http://example.com/twitter.html -->
<!DOCTYPE html>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
</head>
<body>
<h3>Twitter SSE!</h3>
<div id="result"></div>
<script>
var source = new EventSource('http://www.firehose.com/tweets');
// new connection opened callback
source.addEventListener('open', function(e) {
console.log('twitter connection opened');
}, false);
// new connection opened callback
source.addEventListener('message', function(e) {
console.log('tweet received'+e.data);
msg = JSON.parse(e.data);
$('#result').append('<br/>Tweet : ').append(msg.msg);
}, false);
// connection closed callback
source.addEventListener('error', function(e) {
if (e.eventPhase == EventSource.CLOSED) {
console.log('twitter connection closed');
}
}, false);
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment