Created
April 7, 2011 15:00
-
-
Save nolman/907939 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
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 |
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 '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