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 a 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'
# Its Proxy
class Proxy
def run port
begin
# start our server to handle connections (will raise things on errors)
@socket = TCPServer.new port
# handle every request with another method
while true
s = @socket.accept
Thread.new(s) do |r|
handle_request r
end
end
# ctrl-c
rescue Interrupt
puts 'got interrupt..'
# get all possibly errors
rescue => e
puts(e.class.to_s + ': ' + e.message)
# ensure that we release the socket on errors
ensure
if @socket
@socket.close
puts 'socked closed..'
end
puts 'quiting.'
end
end
def handle_request socket
request_line = socket.readline
verb = request_line[/^\w+/]
url = request_line[/^\w+\s+(\S+)/, 1]
uri = URI::parse url
puts url
client = TCPSocket.new(uri.host, 80)
client.write("#{verb} #{uri.path}?#{uri.query} HTTP/1.0\r\n")
loop do
line = socket.readline
# Inject connection: close 'cuz I am lazy
if line.strip.empty?
client.write("Connection: close\r\n\r\n")
break
else
client.write(line)
end
end
answer = client.read
socket.write(answer)
# close the sockets
client.close
socket.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 'Call me like this: 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