The Smallest Proxy?
I needed an http proxy for another project (more on that later) and thought it would be fun to write one in ruby. How simple can it be? With a few compromises, it can be very short indeed:
# tinyproxy.rb
# just for the fun of it
require 'socket'
require 'http-access2'
def process_request(conn)
verb, uri, protocol = conn.gets.split
puts uri
http = HTTPAccess2::Client.new()
resp = http.get(uri)
while HTTP::Status.redirect?(resp.status)
puts "redirect"
resp = http.get(resp.header['location'][0])
end
conn.puts resp.content
conn.close
end
server = TCPServer.new('localhost', 4567)
while (conn = server.accept) do
Thread.new(conn) do |c|
process_request(c)
end
end
I’m cheating in a couple places. I’m only handling GET requests, and I’m using Hiroshi Nakamura’s excellent http-access2 package.
On the other hand, it’s multi-threaded and it handles redirects, a must for the web.
Post a Comment