public
Last active

config.ru for rake-pipeline with proxy support

  • Download Gist
gistfile1.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
require 'rake-pipeline'
require 'rake-pipeline/middleware'
 
require 'net/http'
require 'net/https'
require 'uri'
 
module Rack
class Proxy
def initialize(app, project, opts={})
mode = opts[:mode] || :debug
 
@app = app
@proxy = project
end
 
def call(env)
req = ::Rack::Request.new(env)
method = req.request_method.downcase
method[0..0] = method[0..0].upcase
 
if req.path =~ %r{^#{@proxy['path']}}
uri = URI.parse("#{req.scheme}://#{@proxy['host']}#{ ':'+@proxy['port'].to_s if @proxy['port']}#{req.path}#{ '?'+req.query_string if req.query_string.length > 0}")
 
proxy_request = Net::HTTP.const_get(method).new("#{uri.path}#{'?' if uri.query}#{uri.query}")
 
if proxy_request.request_body_permitted? and req.body
proxy_request.body_stream = req.body
proxy_request.content_length = req.content_length
proxy_request.content_type = req.content_type
end
 
proxy_request['X-Forwarded-For'] = (req.env['X-Forwarded-For'].to_s.split(/, +/) + [req.env['REMOTE_ADDR']]).join(", ")
proxy_request['X-Requested-With'] = req.env['HTTP_X_REQUESTED_WITH'] if req.env['HTTP_X_REQUESTED_WITH']
proxy_request['Accept-Encoding'] = req.accept_encoding
proxy_request['Cookie'] = req.env['HTTP_COOKIE']
proxy_request['Referer'] = req.referer
proxy_request.basic_auth *uri.userinfo.split(':') if (uri.userinfo && uri.userinfo.index(':'))
 
proxy_response = Net::HTTP.start(uri.host, uri.port, :use_ssl => @proxy['use_ssl'] || false) do |http|
http.request(proxy_request)
end
 
headers = {}
proxy_response.each_header do |k,v|
headers[k] = v unless k.to_s =~ /content-length|transfer-encoding/i
end
 
[proxy_response.code.to_i, headers, [proxy_response.read_body]]
else
@app.call(env)
end
end
end
end
 
project = {}
project["port"] = 8080
project["path"] = "/api"
project["host"] = "localhost"
 
use Rake::Pipeline::Middleware, "Assetfile"
use Rack::Proxy, project
run Rack::Directory.new('.')

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.