Permalink
Switch branches/tags
Find file
Fetching contributors…
Cannot retrieve contributors at this time
103 lines (83 sloc) 2.13 KB
#
# streaming response body
#
run proc {|env|
EM.add_timer(1) {
env["stream.start"].call 200, "Content-Type" => "image/png"
EM.add_periodic_timer(1) { env["stream.send"].call "\n" }
}
EM.add_timer(10) { env["stream.close"].call }
[-1, {}, []]
# or instantly:
EM.add_periodic_timer(1) { env["stream.send"].call "\n" }
EM.add_timer(10) { env["stream.close"].call }
[200, {"Content-Type" => "image/png"}, Rack::STREAMING]
}
#
# async response (though all responses are async by default, anyway)
#
run proc {|env|
Fiber.new {
do_something
env["async.callback"].call [201, {"Content-Type" => "text/plain"}, ["Great!"]]
}.resume
[-1, {}, []]
}
#
# streaming request body
#
run proc {|env|
# will return when the input is write-closed
env["rack.input"].receive {|chunk| }
# same here
env["rack.input"].sync
File.open("input.dat", "w") {|f| f << env["rack.input"] }
[201, {"The" => "headers"}, []]
}
#
# proxying
#
class MySimpleProxy
def initialize(env)
@env = env
end
def call(response)
@env["async.callback"].call response
# or modify the ouput via streaming:
@env["stream.start"].call *response[0..1]
response[2].each do |chunk|
@env["stream.send"].call chunk.upcase
end
@env["stream.close"].call
end
end
class MyProxy
def initialize(env)
@env = env
end
def call(response)
@env["proxy.start_reverse"].call *response[0..1]
end
end
class MyApp
def headers(env)
shard = sharding_func.call env["REQUEST_URI"]
# env["rity.callback"] = MySimpleProxy.new(env)
env["proxy.callback"] = MyProxy.new(env)
env["proxy.start"].call shard.uri, "X-Sharding-Func" => "skip"
end
end
run MyApp.new
# or in short:
run proc {|env|
shard = sharding_func.call(env["REQUEST_URI"])
# if no block is passed to proxy.start, it will use EM's native proxying to
# pass the response to the client
env["proxy.start"].call shard.uri, "Additional" => "headers" do |response|
@env["stream.start"].call *response[0..1]
response[2].each do |chunk|
@env["stream.send"].call chunk.upcase
end
@env["stream.close"].call
end
}