Created
          February 12, 2010 11:31 
        
      - 
      
- 
        Save zigzag/302487 to your computer and use it in GitHub Desktop. 
    The simplest proxy server written in Ruby
  
        
  
    
      This file contains hidden or 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
    
  
  
    
  | myport = 80 | |
| hostname = 'xxx.xxx.xxx.xxx' | |
| port = 80 | |
| server = TCPServer.open(myport) | |
| while true | |
| Thread.start(server.accept) do |client| | |
| s = TCPSocket.open(hostname, port) | |
| req_content_length = 0 | |
| while line = client.gets | |
| line.gsub!('google.cn','google.com') | |
| puts line if (line.include?('GET') || line.include?('POST')) | |
| s.puts line | |
| req_content_length = line.split(':')[1].to_i if line.include? 'Content-Length' | |
| break if line.eql?("\r\n") | |
| end | |
| s.puts client.read(req_content_length) if (req_content_length > 0) | |
| puts '-----------------------------' | |
| is_chunk = false | |
| res_content_length = 0 | |
| while res_head_line = s.gets | |
| res_content_length = res_head_line.split(':')[1].to_i if res_head_line.include? 'Content-Length' | |
| is_chunk = true if res_head_line.strip.downcase.include? 'transfer-encoding: chunked' | |
| client.puts res_head_line | |
| puts res_head_line | |
| break if res_head_line.eql?("\r\n") | |
| end | |
| if is_chunk | |
| chunk_size = s.gets | |
| client.puts chunk_size | |
| while(chunk_size.hex > 0) | |
| client.puts s.read(chunk_size.hex) | |
| client.puts s.gets | |
| chunk_size = s.gets | |
| client.puts chunk_size | |
| end | |
| else | |
| client.puts s.read(res_content_length) if (res_content_length > 0) | |
| end | |
| client.close | |
| end | |
| end | 
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment