Skip to content

Instantly share code, notes, and snippets.

@holysugar
Created July 5, 2011 03:35
Show Gist options
  • Save holysugar/1064220 to your computer and use it in GitHub Desktop.
Save holysugar/1064220 to your computer and use it in GitHub Desktop.
file_saving_proxy_server.rb
#!/usr/bin/env ruby
require 'webrick'
require 'webrick/httpproxy'
require "pathname"
class Dumper
def initialize(dir)
@dir = dir
end
class FileDumper
attr_reader :dir, :time
def initialize(dir, time)
@dir = Pathname(dir)
@time = time
end
def dirname
dir + [(time.to_i/1000).to_s, time.to_f.to_s ].join('/')
end
def mkdir
FileUtils.mkdir_p(dirname)
end
def record(name, &block)
open(dirname + name, 'w') {|f| block.call(f) }
end
def touch(name)
open(dirname + name, 'w') {|f| f.print "" }
end
def url_to_filename(url)
url = url.dup
url.query = '' if url.query
url.to_s.gsub(/[^0-9a-z%_-]+/i, '_')
end
def save_req(req)
url = req.request_uri
touch(url_to_filename(url))
method = req.request_method
touch(method)
record("URL") {|f| f.puts url.to_s }
record("request-header.txt"){|f| f.print req.raw_header.join }
record("request-body"){|f| f.print req.body } if ["POST","PUT"].include?(method)
end
def save_res(res)
record("#{res.status}"){|f| f.puts res.status }
record("response-header.txt"){|f| res.each{|k,v| f.puts "#{k}: #{v}" }}
record("response-body"){|f| f.print res.body }
end
end
def save(req, res)
d = FileDumper.new(@dir, Time.now)
d.mkdir
d.save_req(req)
d.save_res(res)
end
end
class DumpProxy < WEBrick::HTTPProxyServer
class << self
def handler(dumper)
proc{|req,res|
# FILTER!
#if req.host =~ /mydomain.example.jp/
dumper.save(req, res)
#end
}
end
def create(dir)
dumper = Dumper.new(dir)
new(
:Port => 3234,
:Logger => WEBrick::Log.new($stderr, WEBrick::Log::DEBUG),
:ProxyVia => false,
:ProxyContentHandler => handler(dumper)
)
end
end
end
s = DumpProxy.create("/tmp/pathto/proxydata")
Signal.trap('INT') do
s.shutdown
end
s.start
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment