hchoroomi (owner)

Fork Of

gist: 57565 by jamis A trivial HTTP proxy server...

Revisions

gist: 57572 Download_button fork
public
Description:
HTTP proxy server
Public Clone URL: git://gist.github.com/57572.git
Embed All Files: show embed
http-proxy-server.rb #
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# 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