Skip to content

Instantly share code, notes, and snippets.

@taf2
Created January 24, 2011 18:21
Show Gist options
  • Save taf2/793651 to your computer and use it in GitHub Desktop.
Save taf2/793651 to your computer and use it in GitHub Desktop.
require 'em-proxy'
host = "0.0.0.0"
port = 9889
puts "listening on #{host}:#{port}..."
Sessions = {}
Proxy.start(:host => host, :port => port) do |conn|
conn.on_connect do|data,b|
puts [:on_connect, data, b].inspect
end
# modify / process request stream
conn.on_data do |data|
if data.match(/^[GET|POST]/)
raw_headers = data.split("\n").map{|h| h.strip }
req_method = raw_headers.shift
headers = {}
raw_headers.each do|kv|
next if kv.strip == ''
key = kv.gsub(/:.*$/,'').strip.downcase
value = kv.gsub(/.*:/,'').strip
headers[key] = value
end
session_token = "#{headers['host']}_#{Time.now.to_i}_#{req_method}"
session_port = headers['host'].split(':').last.to_i || 80
session_port = 80 if session_port == 0
puts "using port: #{session_port.inspect}"
conn.server session_token, :host => headers['host'], :port => session_port
#puts [:on_data, data].inspect
puts "New session: #{session_token} (#{req_method})"
end
data
end
# modify / process response stream
conn.on_response do |backend, resp|
puts [:on_response, backend, resp].inspect
resp
end
# termination logic
conn.on_finish do |backend, name|
puts [:on_finish, name].inspect
# terminate connection (in duplex mode, you can terminate when prod is done)
# unbind if backend == :srv
end
end
@taf2
Copy link
Author

taf2 commented Jan 24, 2011

Revised to change the conn server identifier by request name...

@taf2
Copy link
Author

taf2 commented Jan 24, 2011

Having some problems with this approach - connections are definitely getting mixed... so the wrong response is being sent to some requests...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment