Sha256: f772da92b27166e5734392df2092ecd41b0f4fc00b1c6724e9ccf7cc9e4f6afd

Contents?: true

Size: 1.73 KB

Versions: 12

Compression:

Stored size: 1.73 KB

Contents

# frozen_string_literal: true

# Released under the MIT License.
# Copyright, 2018-2023, by Samuel Williams.

require 'async/http/client'

module Falcon
	module Middleware
		# A static middleware which always returns a 404 not found response.
		module NotFound
			def self.call(request)
				return Protocol::HTTP::Response[404, {}, []]
			end
			
			def self.close
			end
		end
		
		# A HTTP middleware for redirecting a given set of hosts to a different endpoint.
		# Typically used for implementing HTTP -> HTTPS redirects.
		class Redirect < Protocol::HTTP::Middleware
			# Initialize the redirect middleware.
			# @parameter app [Protocol::HTTP::Middleware] The middleware to wrap.
			# @parameter hosts [Hash(String, Service::Proxy)] The map of hosts.
			# @parameter endpoint [Endpoint] The template endpoint to use to build the redirect location.
			def initialize(app, hosts, endpoint)
				super(app)
				
				@hosts = hosts
				@endpoint = endpoint
			end
			
			# Lookup the appropriate host for the given request.
			# @parameter request [Protocol::HTTP::Request]
			def lookup(request)
				# Trailing dot and port is ignored/normalized.
				if authority = request.authority&.sub(/(\.)?(:\d+)?$/, '')
					return @hosts[authority]
				end
			end
			
			# Redirect the request if the authority matches a specific host.
			# @parameter request [Protocol::HTTP::Request]
			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
		end
	end
end

Version data entries

12 entries across 12 versions & 1 rubygems

Version Path
falcon-0.47.9 lib/falcon/middleware/redirect.rb
falcon-0.47.8 lib/falcon/middleware/redirect.rb
falcon-0.47.7 lib/falcon/middleware/redirect.rb
falcon-0.47.1 lib/falcon/middleware/redirect.rb
falcon-0.47.0 lib/falcon/middleware/redirect.rb
falcon-0.46.1 lib/falcon/middleware/redirect.rb
falcon-0.46.0 lib/falcon/middleware/redirect.rb
falcon-0.45.2 lib/falcon/middleware/redirect.rb
falcon-0.45.1 lib/falcon/middleware/redirect.rb
falcon-0.45.0 lib/falcon/middleware/redirect.rb
falcon-0.44.0 lib/falcon/middleware/redirect.rb
falcon-0.43.0 lib/falcon/middleware/redirect.rb