lib/net/http/server/responses.rb in net-http-server-0.1.0 vs lib/net/http/server/responses.rb in net-http-server-0.2.0
- old
+ new
@@ -1,5 +1,7 @@
+require 'net/http/server/chunked_stream'
+
require 'net/protocol'
require 'time'
module Net
class HTTP < Protocol
@@ -123,10 +125,30 @@
stream.flush
end
end
#
+ # Writes the body of a HTTP Response to a stream, using Chunked
+ # Transfer-Encoding.
+ #
+ # @param [IO] stream
+ # The stream to write the headers back to.
+ #
+ # @param [#each] body
+ # The body of the HTTP Response.
+ #
+ # @since 0.2.0
+ #
+ def write_body_streamed(stream,body)
+ chunked_stream = ChunkedStream.new(stream)
+
+ body.each { |chunk| chunked_stream.write(chunk) }
+
+ chunked_stream.close
+ end
+
+ #
# Writes a HTTP Response to a stream.
#
# @param [IO] stream
# The stream to write the HTTP Response to.
#
@@ -140,10 +162,19 @@
# The body of the HTTP Response.
#
def write_response(stream,status,headers,body)
write_status stream, status
write_headers stream, headers
- write_body stream, body
+
+ if headers['Transfer-Encoding'] == 'chunked'
+ write_body_streamed stream, body
+ else
+ write_body stream, body
+
+ # if neither `Content-Length` or `Transfer-Encoding`
+ # were specified, close the stream after writing the response.
+ stream.close unless headers['Content-Length']
+ end
end
end
end
end