Skip to content

Instantly share code, notes, and snippets.

@nolman
Created April 7, 2011 15:00
Show Gist options
  • Save nolman/907939 to your computer and use it in GitHub Desktop.
Save nolman/907939 to your computer and use it in GitHub Desktop.
class ForwardingSupport
def initialize(app)
@app = app
end
def call(env)
async_cb = env['async.callback']
env['async.callback'] = Proc.new do |status, headers, body|
async_cb.call(post_process(env, status, headers, body))
end
status, headers, body = @app.call(env)
post_process(env, status, headers, body)
end
def post_process(env, status, headers, body)
body = body.first if body.is_a?(Array)
return [status, headers, body] unless env.params['forward_to']
begin
body = Yajl::Parser.parse(body) if body.is_a?(String)
uri = Addressable::URI.parse(env.params['forward_to'])
uri.query_values = (uri.query_values || {}).merge(body)
http = EM::HttpRequest.new(uri).get(:redirects => 1)
[200, http.response_header, http.response]
rescue Exception => ex
[status, headers, body]
end
end
end
class Fixnum
def to_str
self.to_s
end
end
require 'goliath'
require File.expand_path(File.join(File.dirname(__FILE__), 'forwarding_support'))
require 'em-synchrony/em-http'
class RequestProxy < Goliath::API
use ForwardingSupport
use Goliath::Rack::Params # parse query & body params
use Goliath::Rack::Formatters::JSON # JSON output formatter
use Goliath::Rack::Render # auto-negotiate response format
use Goliath::Rack::ValidationError # catch and render validation errors
use Goliath::Rack::Validation::RequiredParam, {:key => 'url'}
def response(env)
http = EM::HttpRequest.new(params['url']).get(:redirects => 1)
logger.info "Received #{http.response_header.status} from #{params['url']}"
[200, http.response_header, http.response]
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment