Last active
August 29, 2015 14:00
-
-
Save JoshCheek/8a8836a4a171f11013bb to your computer and use it in GitHub Desktop.
A middleware I wrote to redirect requests to the herokuapp domain over to apply.turing.io
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 YouKnowWeHaveASubdomainNowMiddleware | |
MovedPermanentlyCode = 301 | |
def initialize(app, attributes) | |
self.app = app | |
self.from = attributes.fetch :from | |
self.to = attributes.fetch :to | |
end | |
def call(env) | |
request = Rack::Request.new(env) | |
if request.base_url == from | |
location = to + request.path | |
[MovedPermanentlyCode, {"Location" => location}, []] | |
else | |
app.call env | |
end | |
end | |
private | |
attr_accessor :app, :from, :to | |
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_relative '../test_helper' | |
class YouKnowWeHaveASubdomainNowMiddlewareTest < Minitest::Test | |
def app | |
@app ||= ->(env) { [200, env, "app"] } | |
end | |
FROM = 'http://asquared.herokuapp.com' | |
TO = 'http://apply.turing.io' | |
def middleware | |
@middleware ||= YouKnowWeHaveASubdomainNowMiddleware.new(app, from: FROM, to: TO) | |
end | |
def env_for(url, opts={}) | |
Rack::MockRequest.env_for(url, opts) | |
end | |
def test_redirects_from_FROM_to_TO | |
code, headers = middleware.call env_for "#{FROM}/some/path" | |
assert_equal 301, code | |
assert_equal "#{TO}/some/path", headers['Location'] | |
end | |
def test_does_not_redirect_if_from_is_not_FROM | |
code, headers, message = middleware.call env_for "#{TO}/some/path" | |
assert_equal 200, code | |
assert_equal 'app', message | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment