Skip to content

Instantly share code, notes, and snippets.

@phorsfall
Forked from jamis/http-proxy-server.rb
Created February 3, 2009 21:42
Show Gist options
  • Save phorsfall/57780 to your computer and use it in GitHub Desktop.
Save phorsfall/57780 to your computer and use it in GitHub Desktop.
# This is a trivial HTTP proxy server, intended for use as a troubleshooting tool
# ONLY (not for real, actual, production use). I wrote this because I couldn't find
# a simple HTTP proxy that I could use to test HTTP proxy support in Net::SSH.
#
# This code is in the public domain, so do with it what you will!
require 'socket'
server = TCPServer.new('127.0.0.1', 8080)
client = server.accept
request = client.readline
headers = {}
loop do
line = client.readline.strip
break if line.empty?
key, value = line.split(/:\s*/, 2)
headers[key.downcase] = value
end
if request =~ /^CONNECT (.*?):(\d+) HTTP/
host = $1
port = $2.to_i
puts "starting proxy to #{host}:#{port}"
client.write "HTTP/1.0 200 OK\r\n\r\n"
proxy = TCPSocket.new(host, port)
loop do
r, = IO.select([client, proxy])
if r.include?(client)
data = client.recv(1024)
break if data.nil? || data.empty?
proxy.write(data)
end
if r.include?(proxy)
data = proxy.recv(1024)
break if data.nil? || data.empty?
client.write(data)
end
end
proxy.close
else
puts "not a CONNECT request #{request.inspect}"
end
client.close
server.close
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment