Skip to content

Instantly share code, notes, and snippets.

@MichaelPoP
Forked from torsten/proxy.rb
Created April 28, 2017 18:51
Show Gist options
  • Select an option

  • Save MichaelPoP/5edf9a04e984b10e52e6590b701dfa5e to your computer and use it in GitHub Desktop.

Select an option

Save MichaelPoP/5edf9a04e984b10e52e6590b701dfa5e to your computer and use it in GitHub Desktop.
A quick HTTP proxy server in Ruby.
#!/usr/bin/env ruby
# A quick and dirty implementation of an HTTP proxy server in Ruby
# because I did not want to install anything.
#
# Copyright (C) 2009 Torsten Becker <torsten.becker@gmail.com>
require 'socket'
require 'uri'
class Proxy
def run port
begin
# Start our server to handle connections (will raise things on errors)
@socket = TCPServer.new port
# Handle every request in another thread
loop do
s = @socket.accept
Thread.new(s, &method(:handle_request))
end
# CTRL-C
rescue Interrupt
puts 'Got Interrupt..'
# Ensure that we release the socket on errors
ensure
if @socket
@socket.close
puts 'Socked closed..'
end
puts 'Quitting.'
end
end
def handle_request to_client
request_line = to_client.readline
verb = request_line[/^\w+/]
url = request_line[/^\w+\s+(\S+)/, 1]
uri = URI::parse url
# Show what got requested
puts(("%6s "%verb) + url)
to_server = TCPSocket.new(uri.host, (uri.port.nil? ? 80 : uri.port))
to_server.write("#{verb} #{uri.path}?#{uri.query} HTTP/1.1\r\n")
loop do
line = to_client.readline
# Strip proxy headers
if line =~ /^proxy/i
next
# Inject connection: close 'cuz I am lazy
elsif line.strip.empty?
to_server.write("Connection: close\r\n\r\n")
break
else
to_server.write(line)
end
end
answer = to_server.read
to_client.write(answer)
# Close the sockets
to_client.close
to_server.close
end
end
# Get parameters and start the server
if ARGV.empty?
port = 8008
elsif ARGV.size == 1
port = ARGV[0].to_i
else
puts 'Usage: proxy.rb [port]'
exit 1
end
Proxy.new.run port
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment