Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

Adding support for streaming responses.

  • Loading branch information...
commit 4209c3daf167cbb655712224f89bb61cd11d9345 1 parent 47b0690
@SebastianEdwards authored
View
2  lib/reel.rb
@@ -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
View
32 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
View
14 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
Please sign in to comment.
Something went wrong with that request. Please try again.