Skip to content

Instantly share code, notes, and snippets.

@macks
Created March 31, 2015 21:17
Show Gist options
  • Save macks/b31bbce71e336d804a47 to your computer and use it in GitHub Desktop.
Save macks/b31bbce71e336d804a47 to your computer and use it in GitHub Desktop.
require 'webrick'
require 'webrick/httpproxy'
require 'optparse'
require 'fileutils'
opts = {
port: 8080,
outdir: '.',
}
optparse = OptionParser.new("USAGE: #{$0} [OPTIONS]", 20)
optparse.on('-p PORT', Integer) {|x| opts[:port] = x }
optparse.on('-o DIR') {|x| opts[:outdir] = x }
begin
optparse.parse!
rescue OptionParser::ParseError => e
$stderr.puts e.to_s
exit 1
end
auth_handler = proc do |req, res|
req.header.delete('if-modified-since')
end
content_handler = proc do |req, res|
next if req.request_method != 'GET'
next if res.status != 200
uri = req.request_uri
path = File.join(opts[:outdir], uri.host) # FIXME: Add port number
path << uri.request_uri
path << 'index.html' if path.end_with?('/')
path.gsub!(/\?/, '__')
dir = File.dirname(path)
FileUtils.mkdir_p(dir) unless File.exists?(dir)
IO.binwrite(path, res.body)
if last_modified = res['last-modified']
last_modified = Time.httpdate(last_modified)
File.utime(Time.now, last_modified, path)
end
end
server = WEBrick::HTTPProxyServer.new(
Port: opts[:port],
ProxyAuthProc: auth_handler,
ProxyContentHandler: content_handler
)
trap(:INT) { server.shutdown }
server.start
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment