pub struct Router { /* private fields */ }Expand description
A type that can contain hosts and a root resource.
The Router passes the request to a host that matches the request’s ‘Host’ or
to a root resource if one exists when there is no matching host. Otherwise, it
responds with 404 Not Found.
Implementations§
Source§impl Router
impl Router
Sourcepub fn add_host<H, const N: usize>(&mut self, new_hosts: H)where
H: IntoArray<Host, N>,
pub fn add_host<H, const N: usize>(&mut self, new_hosts: H)where
H: IntoArray<Host, N>,
Adds the given host(s).
use argan::{Router, Host, Resource};
let mut host = Host::new("http://example.com", Resource::new("/"));
let mut host_with_sub = Host::new("http://abc.example.com", Resource::new("/"));
let mut router = Router::new();
router.add_host([host, host_with_sub]);If a new host has a duplicate among the existing hosts, their resource trees will be merged. See also the panics below.
use argan::{Router, Host, Resource, handler::HandlerSetter, http::Method};
let mut router = Router::new();
let mut root = Resource::new("/");
root
.subresource_mut("/resource_1/resource_2/resource_3")
.set_handler_for(Method::GET.to(|| async {}));
router.add_host(Host::new("example.com", root));
let mut root = Resource::new("/");
root.subresource_mut("/resource_1/resource_2")
.set_handler_for(Method::GET.to(|| async {}));
router.add_host(Host::new("example.com", root));§Panics
- if a new host has a duplicate among the existing hosts and both of them have some resource with the same path and both of those resources have some handler set or a middleware applied
use argan::{Router, Host, Resource, handler::HandlerSetter, http::Method};
let mut router = Router::new();
let mut root = Resource::new("/");
root
.subresource_mut("/resource_1/resource_2/resource_3")
.set_handler_for(Method::GET.to(|| async {}));
router.add_host(Host::new("example.com", root));
let mut root = Resource::new("/");
let mut resource_2 = root.subresource_mut("/resource_1/resource_2");
resource_2.set_handler_for(Method::GET.to(|| async {}));
resource_2
.subresource_mut("/resource_3")
.set_handler_for(Method::GET.to(|| async {}));
// This doesn't try to merge the handler sets of the duplicate resources.
router.add_host(Host::new("example.com", root));Sourcepub fn add_resource<R, const N: usize>(&mut self, new_resources: R)where
R: IntoArray<Resource, N>,
pub fn add_resource<R, const N: usize>(&mut self, new_resources: R)where
R: IntoArray<Resource, N>,
Adds the given resource(s).
use argan::{Router, Resource};
let host_resource = Resource::new("http://example.com/resource");
let root = Resource::new("/");
let mut router = Router::new();
router.add_resource([host_resource, root]);In the above example, Router will have a host with the pattern “example.com”
and a root resource.
§Panics
- if the resource or one of its subresources has a duplicate in the existing parent’s subtree and both of them have some handler set or a middleware applied
use argan::{Router, Resource, handler::HandlerSetter, http::Method};
let mut router = Router::new();
let mut resource_3 = Resource::new("/resource_1/resource_2/resource_3");
resource_3.set_handler_for(Method::GET.to(|| async {}));
router.add_resource(resource_3);
let mut resource_2 = Resource::new("/resource_1/resource_2");
let mut resource_3 = Resource::new("/resource_3");
resource_3.set_handler_for(Method::POST.to(|| async {}));
resource_2.add_subresource(resource_3);
// This doesn't try to merge the handler sets of the duplicate resources.
router.add_resource(resource_2);Sourcepub fn add_resource_under<U, R, const N: usize>(
&mut self,
uri_pattern: U,
new_resources: R,
)
pub fn add_resource_under<U, R, const N: usize>( &mut self, uri_pattern: U, new_resources: R, )
Adds the given resources under the prefix URI components.
use argan::{Router, Resource};
let resource_2_0 = Resource::new("/resource_2_0");
let resource_2_1 = Resource::new("/resource_2_1");
let mut router = Router::new();
router.add_resource_under("http://example.com/resource_1", [resource_2_0, resource_2_1]);§Panics
- if the new resource’s URI components don’t match the given prefix URI components
use argan::{Router, Resource};
let mut router = Router::new();
let resource_3 = Resource::new("/resource_1/resource_2/resource_3");
router.add_resource_under("/some_resource", resource_3);Other panic conditions are the same as add_resource()’s conditions.
Sourcepub fn resource_mut<U>(&mut self, uri_pattern: U) -> &mut Resource
pub fn resource_mut<U>(&mut self, uri_pattern: U) -> &mut Resource
Returns the resource at the given URI. If the resource doesn’t exist, it will be created.
use argan::Router;
let mut router = Router::new();
let resource_2 = router.resource_mut("http://example.com/resource_1/resource_2");§Panics
- if the given URI is empty
- if the URI contains only a path and it doesn’t start with a slash
/ - if the resource has some handler set or middleware applied, and the given configuration symbols don’t match its configuration
use argan::{Router, handler::HandlerSetter, http::Method};
let mut router = Router::new();
router.resource_mut("/resource_1 !*").set_handler_for([
Method::GET.to(|| async {}),
Method::POST.to(|| async {}),
]);
// ...
let resource_1 = router.resource_mut("/resource_1");For configuration symbols, see the crate documentation;
Sourcepub fn set_extension<E: Clone + Send + Sync + 'static>(&mut self, extension: E)
pub fn set_extension<E: Clone + Send + Sync + 'static>(&mut self, extension: E)
Sets the given extension to the Router. The extension is available to all middleware
that wraps the Router’s request passer in the NodeExtension field of the
Args.
§Panics
- if the
Routeralready has an extension set
Sourcepub fn wrap<L, const N: usize>(&mut self, layer_targets: L)where
L: IntoArray<LayerTarget<Self>, N>,
pub fn wrap<L, const N: usize>(&mut self, layer_targets: L)where
L: IntoArray<LayerTarget<Self>, N>,
Adds middleware to be applied on the router’s request passer.
Middlewares are applied when the router is being converted into a service.
use std::time::Duration;
use argan::prelude::*;
use tower_http::timeout::TimeoutLayer;
#[derive(Clone)]
struct MiddlewareLayer;
impl<H> Layer<H> for MiddlewareLayer
where
H: Handler + Clone + Send + Sync,
{
type Handler = Middleware<H>;
fn wrap(&self, handler: H) -> Self::Handler {
Middleware(handler)
}
}
#[derive(Clone)]
struct Middleware<H>(H);
impl<H> Handler for Middleware<H>
where
H: BoxableHandler,
{
type Response = Response;
type Error = BoxedErrorResponse;
type Future = BoxedFuture<Result<Self::Response, Self::Error>>;
fn handle(&self, request_context: RequestContext, args: Args<'_, ()>) -> Self::Future {
// ...
let response_future = self.0.handle(request_context, args);
Box::pin(async move {
let response = response_future.await?;
// ...
Ok(response)
})
}
}
// ...
let mut router = Router::new();
router.wrap(RequestPasser.component_in(
(TimeoutLayer::new(Duration::from_millis(64)), MiddlewareLayer),
));Sourcepub fn set_property<C, const N: usize>(&mut self, properties: C)where
C: IntoArray<NodeProperty<Self>, N>,
pub fn set_property<C, const N: usize>(&mut self, properties: C)where
C: IntoArray<NodeProperty<Self>, N>,
Sets the router’s optional properties.
use argan::{Router, common::node_properties::NodeCookieKey, data::cookies::Key};
let mut router = Router::new();
// Given `cookie::Key` will be available to all resoruces unless some resource
// or handler replaces it with its own `cookie::Key` while the request is being
// routed or handled.
router.set_property(NodeCookieKey.to(Key::generate()));Sourcepub fn for_each_root<T, F>(&mut self, param: T, func: F) -> T
pub fn for_each_root<T, F>(&mut self, param: T, func: F) -> T
Calls the given function for each root resource (hosts’ and router’s) with a mutable
reference to the param.
All the variants of Iteration other than Stop are ignored. If the function retuns
Iteration::Stop or all the root resources have beeen processed, the parameter is
returned in its final state.
Sourcepub fn into_service(self) -> RouterService
pub fn into_service(self) -> RouterService
Converts the Router into a service.
Sourcepub fn into_arc_service(self) -> ArcRouterService
pub fn into_arc_service(self) -> ArcRouterService
Converts the Router into a service that uses Arc internally.
Sourcepub fn into_leaked_service(self) -> LeakedRouterService
pub fn into_leaked_service(self) -> LeakedRouterService
Converts the Router into a service with a leaked &'static.