-
-
Save siuying/1560703 to your computer and use it in GitHub Desktop.
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 'rubygems' | |
require 'em-proxy' | |
require 'http_tools' | |
require 'uuid' | |
# > ruby em-proxy-http.rb | |
# > curl --proxy localhost:8080 www.google.com | |
host = "0.0.0.0" | |
port = 8080 | |
puts "listening on #{host}:#{port}..." | |
Proxy.start(:host => host, :port => port) do |conn| | |
@req_parser = HTTPTools::Parser.new | |
@req_parser.on(:finish) do | |
session = UUID.generate | |
host, port = @req_parser.header['Host'].split(':') | |
conn.server session, :host => host, :port => (port || 80) | |
@req_parser.header.delete("Host") | |
@req_parser.header["Connection"] = "close" | |
@req_parser.header["Proxy-Connection"] = "close" | |
conn.relay_to_servers HTTPTools::Builder.request(@req_parser.request_method, "#{host}:#{port}", @req_parser.path_info, @req_parser.header) | |
conn.relay_to_servers @req_parser.body | |
end | |
conn.on_connect do |data,b| | |
puts [:on_connect, data, b].inspect | |
end | |
conn.on_data do |data| | |
@req_parser << data | |
data | |
end | |
@resp_parser = HTTPTools::Parser.new | |
@resp_parser.on(:finish) do | |
@resp_parser.header["Connection"] = "close" | |
@resp_parser.header["Transfer-Encoding"] = "identity" | |
header = HTTPTools::Builder.response(@resp_parser.status_code, @resp_parser.header) | |
conn.send_data header | |
conn.send_data @resp_parser.body if @resp_parser.body | |
puts [:on_response, header, @resp_parser.body].inspect | |
end | |
conn.on_response do |backend, resp| | |
@resp_parser << resp | |
nil | |
end | |
conn.on_finish do |backend, name| | |
puts [:on_finish, name].inspect | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment