Skip to content

Instantly share code, notes, and snippets.

@eidge
Created December 11, 2017 20:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eidge/3a09b840ad2fa6cfdd702f1e9ee26970 to your computer and use it in GitHub Desktop.
Save eidge/3a09b840ad2fa6cfdd702f1e9ee26970 to your computer and use it in GitHub Desktop.
require 'socket'
require 'uri'
class Proxy
def initialize(port)
@port = port
end
attr_reader :port
def start
print "Starting proxy on port #{port}\n"
socket = TCPServer.new port
loop do
client_socket = socket.accept
Thread.new(client_socket, &method(:proxy_request))
end
ensure
socket && socket.close
end
private
def proxy_request(client_socket)
print "Got client\n"
request_line = client_socket.readline
print request_line
verb = request_line[/^\w+/]
url = request_line[/^\w+\s+(\S+)/, 1]
version = request_line[/HTTP\/(1\.\d)\s*$/, 1]
uri = URI::parse url
to_socket = TCPSocket.new(uri.host, (uri.port.nil? ? 80 : uri.port))
to_socket.write("#{verb} #{uri.path}?#{uri.query} HTTP/#{version}\r\n")
content_len = 0
loop do
line = client_socket.readline
print line
to_socket.write(line)
break if line.strip.empty?
end
answer = to_socket.read
client_socket.write(answer)
client_socket.close
print "Socket closed\n"
rescue Exception => e
p e
end
end
Proxy
.new(3001)
.start
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment