Last active
February 5, 2019 14:23
-
-
Save flash-gordon/3320129714a75448cbdbe0de6ec174b0 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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