Skip to content

Instantly share code, notes, and snippets.

@suzumura-ss
Last active December 22, 2015 00:32
Show Gist options
  • Save suzumura-ss/50bdd58792302830a8b8 to your computer and use it in GitHub Desktop.
Save suzumura-ss/50bdd58792302830a8b8 to your computer and use it in GitHub Desktop.
Rack middleware for process X-Reproxy-URL.
=begin
require 'grape'
require 'x_reproxy_url_filter'
class Hello < Grape::API
get 'static' do
status 200
%w{The quick brown fox jumps over the lazy dog}
end
get 'download' do
status 204
header XReproxyUrlFilter::X_REPROXY_URL, 'http://localhost/static'
end
end
use XReproxyUrlFilter
run Hello
=end
require 'open-uri'
require 'rest-client'
class XReproxyUrlFilter
BYPASS_KEYS = %w{content-type content-length}
X_REPROXY_URL = 'x_reproxy_url'
class Adapter
def initialize(uri)
@uri = uri
RestClient.head(uri){|response, request, result, &block|
@res = result
response.return!(request, result, &block)
}
end
def each(&block)
Kernel.open(@uri){|res|
res.each(&block)
}
end
def to_rack_response
headers = @res.each_header.select{|k,v| BYPASS_KEYS.include?(k)}.to_h
[@res.code.to_i, headers, self]
end
end
def initialize(app)
@app = app
end
def call(env)
res = @app.call(env)
url = res[1][X_REPROXY_URL]
return res unless url
Adapter.new(url).to_rack_response
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment