forked from celluloid/reel
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Adding support for streaming responses.
- Loading branch information
1 parent
47b0690
commit 4209c3d
Showing
3 changed files
with
48 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -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 |