Created
February 15, 2012 14:25
-
-
Save osdrv/1836102 to your computer and use it in GitHub Desktop.
json-p proxy for any json
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
#encoding: utf-8 | |
class Object | |
def try(method) | |
send method if respond_to? method | |
end | |
end | |
require "eventmachine" | |
require "evma_httpserver" | |
require "em-http-request" | |
require "cgi" | |
require "uri" | |
class JSONHTTPProxy < EM::Connection | |
include EM::HttpServer | |
def post_init | |
super | |
no_environment_strings | |
end | |
def process_http_request | |
response = EM::DelegatedHttpResponse.new(self) | |
params = @http_query_string.nil? ? Hash.new : CGI.parse(@http_query_string) | |
url = [params["u"], params["url"]].delete_if{|e|e.nil?||e.length==0}.first.try(:first) | |
handler = [params["jsonp"], params["h"], params["cb"], params["handler"], params["callback"]].delete_if{|e|e.nil?||e.length==0}.first.try(:first) | |
if (url =~ URI::regexp).nil? | |
response.status = 406 | |
response.send_response | |
else | |
http = EventMachine::HttpRequest.new( url ).get | |
http.callback do | |
response.status = http.response_header.status | |
response.content_type "application/json" | |
if handler.nil? || handler[/^[\w\d\_]+$/].nil? | |
response.content = http.response | |
else | |
handler = "window.#{handler}" | |
response.content = "#{handler}(#{http.response.chomp})" | |
end | |
response.send_response | |
end | |
http.errback do | |
response.status = 500 | |
response.send_response | |
end | |
end | |
end | |
end | |
EM.run{ | |
EM.start_server '0.0.0.0', 7070, JSONHTTPProxy | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment