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 BuilderBuilds an immutable route table.
Definitions
def self.build(delegate = Protocol::HTTP::Middleware::NotFound)
Build and configure a frozen router.
Signature
-
parameter
delegateProtocol::HTTP::Middleware The middleware for unmatched requests.
-
yields
{|builder| ...} Configures the routes.
-
parameter
builderBuilder The route builder.
-
parameter
-
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
delegateProtocol::HTTP::Middleware The middleware for unmatched requests.
-
parameter
routesHash 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
requestProtocol::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