Struct Router

Source
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

Source

pub fn new() -> Router

Creates a new Router.

Source

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));
Source

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);
Source

pub fn add_resource_under<U, R, const N: usize>( &mut self, uri_pattern: U, new_resources: R, )
where U: AsRef<str>, R: IntoArray<Resource, N>,

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.

Source

pub fn resource_mut<U>(&mut self, uri_pattern: U) -> &mut Resource
where U: AsRef<str>,

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;

Source

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 Router already has an extension set
Source

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),
));
Source

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()));
Source

pub fn for_each_root<T, F>(&mut self, param: T, func: F) -> T
where F: FnMut(&mut T, &mut Resource) -> Iteration,

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.

Source

pub fn into_service(self) -> RouterService

Converts the Router into a service.

Source

pub fn into_arc_service(self) -> ArcRouterService

Converts the Router into a service that uses Arc internally.

Source

pub fn into_leaked_service(self) -> LeakedRouterService

Converts the Router into a service with a leaked &'static.

Trait Implementations§

Source§

impl Default for Router

Source§

fn default() -> Self

Returns the “default value” for a type. Read more

Auto Trait Implementations§

§

impl Freeze for Router

§

impl !RefUnwindSafe for Router

§

impl !Send for Router

§

impl !Sync for Router

§

impl Unpin for Router

§

impl !UnwindSafe for Router

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more