Skip to content

Manually chunked response body. #16

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion config.ru
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
require_relative 'lib/rack/conform/application'
require_relative 'lib/rack/conform'
run Rack::Conform::Application.new
2 changes: 2 additions & 0 deletions lib/rack/conform.rb
Original file line number Diff line number Diff line change
Expand Up @@ -5,3 +5,5 @@

require_relative 'conform/version'
require_relative 'conform/application'

require_relative 'conform/chunked'
41 changes: 41 additions & 0 deletions lib/rack/conform/chunked.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@

module Rack
module Conform
module Chunked
class Body # :nodoc:
TERM = "\r\n"
TAIL = "0#{TERM}"

# Store the response body to be chunked.
def initialize(body)
@body = body
end

# For each element yielded by the response body, yield
# the element in chunked encoding.
def each(&block)
term = TERM
@body.each do |chunk|
size = chunk.bytesize
next if size == 0

yield [size.to_s(16), term, chunk.b, term].join
end
yield TAIL
yield term
end

# Close the response body if the response body supports it.
def close
@body.close if @body.respond_to?(:close)
end
end
end

class Application
def test_chunked_body(env)
[200, {'transfer-encoding' => 'chunked'}, Chunked::Body.new(env['rack.input'])]
end
end
end
end
14 changes: 14 additions & 0 deletions test/rack/conform/streaming/body.rb
Original file line number Diff line number Diff line change
Expand Up @@ -18,3 +18,17 @@
response&.finish
end
end

it 'can stream a chunked response' do
body = Protocol::HTTP::Body::Buffered.new([
"Hello ",
"World!"
])

response = client.post("/chunked/body", {}, body)

expect(response.status).to be == 200
expect(response.read).to be == "Hello World!"
ensure
response&.finish
end