Skip to content

Streaming responses #1600

@ioquatix

Description

@ioquatix

@matthewd gave an example of one option by capturing the stream callback.

For reference, here is a fully working example:

require 'trenni'

class Output < Struct.new(:stream)
	def <<(chunk)
		stream.call chunk
	end
end

class DeferredBody < Struct.new(:later)
	def each(&stream)
		later.call(stream)
	end
end

class App
	def call(env)
		buffer = Trenni::Buffer.new(<<~EOF)
		<?r 10.times do; sleep 1 ?>
		Hello World
		<?r end ?>
		EOF
		
		template = Trenni::Template.new(buffer)
		
		[200, {}, DeferredBody.new(->(stream){ template.to_string({}, Output.new(stream)) })]
	end
end

run App.new
% falcon serve --bind http://localhost
% curl --no-buffer --insecure http://localhost:9292 
		Hello World
		Hello World
		Hello World
		Hello World
		Hello World
		Hello World
		Hello World
		Hello World
		Hello World
		Hello World

It also works for HTTP/2

If we can do this already, is there any point to partial rack.hijack?

@boazsegev do you have any opinion about capturing the stream output this way?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions