class Router < Protocol::HTTP::Middleware

Inherits from
Protocol::HTTP::Middleware

Dispatches HTTP requests to handlers using exact path and method matches.

Request targets are parsed with Protocol::URL::Reference. Handlers receive the original request.

Nested Classes and Modules

class Builder

Builds an immutable route table.

Definitions

def self.build(delegate = Protocol::HTTP::Middleware::NotFound)

Build and configure a frozen router.

Signature

parameter delegate Protocol::HTTP::Middleware

The middleware for unmatched requests.

yields {|builder| ...}

Configures the routes.

parameter builder Builder

The route builder.

returns Router

The configured router.

Implementation

def self.build(delegate = Protocol::HTTP::Middleware::NotFound)
	builder = Builder.new
	yield builder
	
	return new(delegate, builder.routes).freeze
end

def initialize(delegate, routes)

Initialize a router.

Signature

parameter delegate Protocol::HTTP::Middleware

The middleware for unmatched requests.

parameter routes Hash

The frozen route table.

Implementation

def initialize(delegate, routes)
	super(delegate)
	@routes = routes
end

def call(request)

Dispatch a request to a matching route.

Signature

parameter request Protocol::HTTP::Request

The request to dispatch.

returns Protocol::HTTP::Response

The handler, error, or delegate response.

Implementation

def call(request)
	reference = parse_reference(request.path)
	return Protocol::HTTP::Response[400] unless reference
	
	return super unless handlers = @routes[reference.path]
	
	unless handler = handlers[request.method] || handlers[ANY_METHOD]
		allowed_methods = handlers.keys.compact.sort.join(", ")
		return Protocol::HTTP::Response[405, [["allow", allowed_methods]]]
	end
	
	return handler.call(request)
end