class Falcon::Middleware::Redirect

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

def call(request)

@parameter request [Protocol::HTTP::Request]
Redirect the request if the authority matches a specific host.
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
		
		return Protocol::HTTP::Response[301, [['location', location]], []]
	else
		super
	end
end

def initialize(app, hosts, endpoint)

@parameter endpoint [Endpoint] The template endpoint to use to build the redirect location.
@parameter hosts [Hash(String, Service::Proxy)] The map of hosts.
@parameter app [Protocol::HTTP::Middleware] The middleware to wrap.
Initialize the redirect middleware.
def initialize(app, hosts, endpoint)
	super(app)
	
	@hosts = hosts
	@endpoint = endpoint
end

def lookup(request)

@parameter request [Protocol::HTTP::Request]
Lookup the appropriate host for the given request.
def lookup(request)
	# Trailing dot and port is ignored/normalized.
	if authority = request.authority&.sub(/(\.)?(:\d+)?$/, '')
		return @hosts[authority]
	end
end