Skip to content

Instantly share code, notes, and snippets.

@intrip
Created November 4, 2020 11:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save intrip/952452c2a18d254b496045ffef2d8d37 to your computer and use it in GitHub Desktop.
Save intrip/952452c2a18d254b496045ffef2d8d37 to your computer and use it in GitHub Desktop.
require 'webrick'
require 'webrick/httpproxy'
# How to test it
#
# In a terminal:
# $ ruby delay_proxy.rb
#
# In another terminal:
# $ http_proxy=http://localhost:8001 curl http://www.google.it
#
$chunk_size = 10
# the proxy port
$port = 8001
class DelayIO
def initialize(res)
# TODO split the data into tokens with the sleep "<!-- sleep xyx -->" in order to build
# the data chunks to send in intervals.
@data = res.body
end
def readpartial(maxlen, outbuf)
# TODO return the data in chunks with a sleep in between them
# in this example we just split data into fixed chunks
sleep 1
# send data
outbuf << "#{@data[0, $chunk_size]}\n"
# remove processed data
@data = @data[$chunk_size - 1, @data.length - 1]
end
def bytesize
[@data.length, $chunk_size].min
end
def close
# noop
# not a real IO socket
end
end
handler = proc do |req, res|
res.chunked = true
# this is a hack to force the chunk size
res.instance_variable_set('@buffer_size', $chunk_size)
res.body = DelayIO.new(res)
end
# start an http proxy on $port
proxy = WEBrick::HTTPProxyServer.new(Port: $port, ProxyContentHandler: handler)
proxy.start
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment