Skip to content

Instantly share code, notes, and snippets.

@stevenwilkin
Created November 11, 2011 09:47
Show Gist options
  • Save stevenwilkin/1357628 to your computer and use it in GitHub Desktop.
Save stevenwilkin/1357628 to your computer and use it in GitHub Desktop.
#!/usr/bin/env ruby
# serve the contents under www/ with a web server via port 8080 and proxy all
# requests to /api/* to an external API
# Steven Wilkin | @stevebiscuit
require 'net/http'
require 'webrick'
require 'uri'
API_BASE_URL = 'http://0.0.0.0:9292'
class ApiProxy < WEBrick::HTTPServlet::AbstractServlet
def service(request, response)
# original request details
path = request.path_info
method = request.request_method.downcase
headers = request.header.clone
uri = URI(API_BASE_URL)
http = Net::HTTP.new(uri.host, uri.port)
# each value is an array copntaining a single string, get rid of the array
headers.each do |key, value|
headers[key] = headers[key][0]
end
# access the API
if method =~ /post|put/
data = request.body.chomp.strip
api_response = http.send(method, path, data, headers)
else
api_response = http.send(method, path, headers)
end
# return the API response details to originating request
response.status = api_response.code
response['Content-Type'] = api_response['Content-Type']
response.body = api_response.body
end
end
s = WEBrick::HTTPServer.new(
:Port => 8080,
:DocumentRoot => File.join(Dir.pwd, 'www')
)
s.mount '/api', ApiProxy
trap("INT"){ s.shutdown }
s.start
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment