Last active
August 29, 2015 14:02
-
-
Save prashanthrajagopal/cbf14d50c3e7ff324029 to your computer and use it in GitHub Desktop.
A simple proxy server in Ruby
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'net/http' | |
require 'net/https' | |
require 'uri' | |
require 'pry' | |
class Proxy | |
def server(port) | |
puts "Starting Proxy server on port #{port}" | |
@socket = TCPServer.new('localhost', port) | |
loop do | |
s = @socket.accept | |
Thread.new(s, &method(:forward)) | |
end | |
end | |
def forward(from) | |
request = from.recv(1024) | |
url = request[/^\w+\s+(\S+)/, 1] | |
url = URI.parse(url) | |
http = Net::HTTP.new(url.host, url.port) | |
request_uri = url.request_uri | |
http.open_timeout = http.read_timeout = 60 | |
request = Net::HTTP::Get.new(request_uri) | |
response = http.request(request) | |
puts "#{response.body.length} - #{url}" | |
from.write(response.body) | |
from.close | |
end | |
end | |
if ARGV.empty? | |
port = 2345 | |
elsif ARGV.size == 1 | |
port = ARGV[0].to_i | |
else | |
puts 'Usage: proxy.rb [port]' | |
exit 1 | |
end | |
Proxy.new.server port |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment