Skip to content

Commit

Permalink
Adding support for streaming responses.
Browse files Browse the repository at this point in the history
  • Loading branch information
SebastianEdwards committed May 16, 2012
1 parent 47b0690 commit 4209c3d
Show file tree
Hide file tree
Showing 3 changed files with 48 additions and 0 deletions.
2 changes: 2 additions & 0 deletions lib/reel.rb
Expand Up @@ -9,6 +9,8 @@
require 'reel/request'
require 'reel/request/parser'
require 'reel/response'
require 'reel/response/chunked_body'
require 'reel/streaming_response'
require 'reel/server'

# A Reel good HTTP server
Expand Down
32 changes: 32 additions & 0 deletions lib/reel/response/chunked_body.rb
@@ -0,0 +1,32 @@
module Reel
class Response
class ChunkedBody
# Delimiter for chunked encoding
CRLF = "\r\n"

# Final chunk in any chunked-encoding response
FINAL_CHUNK = "0#{CRLF}#{CRLF}"

# Creates a new {ChunkedBody} from the given {Enumerable}.
# @param [Enumerable] body the enumerable response body
# @return [ChunkedBody] the wrapped response body
def initialize(body)
@body = body
end

# Calls the given block once for each chunk, passing that chunk as a
# parameter.
# Returns an {Enumerator} if no block is given.
def each
return self.to_enum unless block_given?

@body.each do |chunk|
size = chunk.bytesize
next if size == 0
yield([size.to_s(16), CRLF, chunk, CRLF].join)
end
yield(FINAL_CHUNK)
end
end
end
end
14 changes: 14 additions & 0 deletions lib/reel/streaming_response.rb
@@ -0,0 +1,14 @@
module Reel
class StreamingResponse < Response
def initialize(*args)
super(*args)
@headers.delete 'Content-Length'
@headers['Transfer-Encoding'] = 'chunked'
end

def render(socket)
socket << render_header
ChunkedBody.new(@body).each {|chunk| socket << chunk }
end
end
end

0 comments on commit 4209c3d

Please sign in to comment.