Skip to content

Commit c666b1c

Browse files
committed
Manually chunked response body.
1 parent e2382a1 commit c666b1c

File tree

4 files changed

+58
-1
lines changed

4 files changed

+58
-1
lines changed

config.ru

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,2 @@
1-
require_relative 'lib/rack/conform/application'
1+
require_relative 'lib/rack/conform'
22
run Rack::Conform::Application.new

lib/rack/conform.rb

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,3 +5,5 @@
55

66
require_relative 'conform/version'
77
require_relative 'conform/application'
8+
9+
require_relative 'conform/chunked'

lib/rack/conform/chunked.rb

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
2+
module Rack
3+
module Conform
4+
module Chunked
5+
class Body # :nodoc:
6+
TERM = "\r\n"
7+
TAIL = "0#{TERM}"
8+
9+
# Store the response body to be chunked.
10+
def initialize(body)
11+
@body = body
12+
end
13+
14+
# For each element yielded by the response body, yield
15+
# the element in chunked encoding.
16+
def each(&block)
17+
term = TERM
18+
@body.each do |chunk|
19+
size = chunk.bytesize
20+
next if size == 0
21+
22+
yield [size.to_s(16), term, chunk.b, term].join
23+
end
24+
yield TAIL
25+
yield term
26+
end
27+
28+
# Close the response body if the response body supports it.
29+
def close
30+
@body.close if @body.respond_to?(:close)
31+
end
32+
end
33+
end
34+
35+
class Application
36+
def test_chunked_body(env)
37+
[200, {'transfer-encoding' => 'chunked'}, Chunked::Body.new(env['rack.input'])]
38+
end
39+
end
40+
end
41+
end

test/rack/conform/streaming/body.rb

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,3 +18,17 @@
1818
response&.finish
1919
end
2020
end
21+
22+
it 'can stream a chunked response' do
23+
body = Protocol::HTTP::Body::Buffered.new([
24+
"Hello ",
25+
"World!"
26+
])
27+
28+
response = client.post("/chunked/body", {}, body)
29+
30+
expect(response.status).to be == 200
31+
expect(response.read).to be == "Hello World!"
32+
ensure
33+
response&.finish
34+
end

0 commit comments

Comments
 (0)