Class: Falcon::Middleware::Redirect

Inherits:
Protocol::HTTP::Middleware
  • Object
show all
Defined in:
lib/falcon/middleware/redirect.rb

Overview

A HTTP middleware for redirecting a given set of hosts to a different endpoint. Typically used for implementing HTTP -> HTTPS redirects.

Instance Method Summary collapse

Constructor Details

#initialize(app, hosts, endpoint) ⇒ Redirect

Initialize the redirect middleware.



31
32
33
34
35
36
# File 'lib/falcon/middleware/redirect.rb', line 31

def initialize(app, hosts, endpoint)
	super(app)
	
	@hosts = hosts
	@endpoint = endpoint
end

Instance Method Details

#call(request) ⇒ Object

Redirect the request if the authority matches a specific host.



49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
# File 'lib/falcon/middleware/redirect.rb', line 49

def call(request)
	if host = lookup(request)
		if @endpoint.default_port?
			location = "#{@endpoint.scheme}://#{host.authority}#{request.path}"
		else
			location = "#{@endpoint.scheme}://#{host.authority}:#{@endpoint.port}#{request.path}"
		end
		
		Console.info(self, "Redirecting incoming request...", request: request, location: location)
		
		return Protocol::HTTP::Response[301, [["location", location]], []]
	else
		super
	end
end

#lookup(request) ⇒ Object

Lookup the appropriate host for the given request.



40
41
42
43
44
45
# File 'lib/falcon/middleware/redirect.rb', line 40

def lookup(request)
	# Trailing dot and port is ignored/normalized.
	if authority = request.authority&.sub(/(\.)?(:\d+)?$/, "")
		return @hosts[authority]
	end
end