Skip to content

Instantly share code, notes, and snippets.

@flash-gordon
Last active February 5, 2019 14:23
Show Gist options
  • Save flash-gordon/3320129714a75448cbdbe0de6ec174b0 to your computer and use it in GitHub Desktop.
Save flash-gordon/3320129714a75448cbdbe0de6ec174b0 to your computer and use it in GitHub Desktop.
require 'rack'
require 'puma'
require 'thread'
class Middleware
def initialize(app)
@app = app
@queue = Queue.new
@thread = Thread.new { run_loop }
end
def call(env)
if delay_response?(env)
response = @app.(env)
io = env["rack.hijack"].()
@queue.push([io, response, Time.now + 5])
[-1, {}, []]
else
@app.(env)
end
end
def delay_response?(env)
true
end
def run_loop
loop do
io, response, at = @queue.pop
delay = at - Time.now
sleep(delay) if delay > 0
code, headers, body = response
io.puts "HTTP/1.1 #{ code }\r\n\r\n#{ body.join }"
io.close
end
end
end
run Middleware.new(->(env) { [200, {}, ["hi"]] })
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment