Sha256: 5b70dd74e4635c8d6ac51586ad833bcf6a029fbc3b2603d8b4535328a1d510b0

Contents?: true

Size: 850 Bytes

Versions: 2

Compression:

Stored size: 850 Bytes

Contents

#!/usr/bin/env ruby
$:<< '../lib' << 'lib'

#
# A simple HTTP streaming API which returns a 200 response for any GET request
# and then emits numbers 1 through 10 in 1 second intervals, and then closes the
# connection.
#
# A good use case for this pattern would be to provide a stream of updates or a
# 'firehose' like API to stream data back to the clients. Simply hook up to your
# datasource and then stream the data to your clients via HTTP.
#

require 'goliath'

class Stream < Goliath::API
  def on_close(env)
    env.logger.info "Connection closed."
  end

  def response(env)
    i = 0
    pt = EM.add_periodic_timer(1) do
      env.stream_send("#{i} ")
      i += 1
    end

    EM.add_timer(10) do
      pt.cancel

      env.stream_send("!! BOOM !!\n")
      env.stream_close
    end

    [200, {}, Goliath::Response::STREAMING]
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
goliath-0.9.1 examples/stream.rb
goliath-0.9.0 examples/stream.rb