Router

Struct Router 

Source
pub struct Router<'path> { /* private fields */ }
Expand description

Router dispatches requests to different handlers via configurable routes.

Implementations§

Source§

impl<'path> Router<'path>

Source

pub fn handle( self, path: &'path str, method: Method, handler: impl Handler + 'static, ) -> Self

Insert a value into the router for a specific path at the specified method.

use httprouter::Router;
use hyper::{Response, Body, Method};

let router = Router::default()
    .handle("/teapot", Method::GET, |_| async {
        Ok(Response::new(Body::from("I am a teapot!")))
    });
Source

pub fn lookup( &self, method: Method, path: impl AsRef<str>, ) -> Result<Match<'_, Box<dyn Handler>>, Tsr>

Lookup allows the manual lookup of handler for a specific method and path. If the handler is not found, it returns a Err(bool) indicating whether a redirection should be performed to the same path with a trailing slash

use httprouter::Router;
use hyper::{Response, Body, Method};

let router = Router::default()
    .get("/home", |_| async {
        Ok(Response::new(Body::from("Welcome!")))
    });

let res = router.lookup(Method::GET, "/home").unwrap();
assert!(res.params.is_empty());
Source

pub fn serve_files()

TODO

Source

pub fn get(self, path: &'path str, handler: impl Handler + 'static) -> Self

Register a handler for GET requests

Source

pub fn head(self, path: &'path str, handler: impl Handler + 'static) -> Self

Register a handler for HEAD requests

Source

pub fn options(self, path: &'path str, handler: impl Handler + 'static) -> Self

Register a handler for OPTIONS requests

Source

pub fn post(self, path: &'path str, handler: impl Handler + 'static) -> Self

Register a handler for POST requests

Source

pub fn put(self, path: &'path str, handler: impl Handler + 'static) -> Self

Register a handler for PUT requests

Source

pub fn patch(self, path: &'path str, handler: impl Handler + 'static) -> Self

Register a handler for PATCH requests

Source

pub fn delete(self, path: &'path str, handler: impl Handler + 'static) -> Self

Register a handler for DELETE requests

Source

pub fn redirect_trailing_slash(self) -> Self

Enables automatic redirection if the current route can’t be matched but a handler for the path with (without) the trailing slash exists. For example if /foo/ is requested but a route only exists for /foo, the client is redirected to /foo with HTTP status code 301 for GET requests and 307 for all other request methods.

Source

pub fn redirect_fixed_path(self) -> Self

If enabled, the router tries to fix the current request path, if no handle is registered for it. First superfluous path elements like ../ or // are removed. Afterwards the router does a case-insensitive lookup of the cleaned path. If a handle can be found for this route, the router makes a redirection to the corrected path with status code 301 for GET requests and 307 for all other request methods. For example /FOO and /..//Foo could be redirected to /foo. redirect_trailing_slash is independent of this option.

Source

pub fn handle_method_not_allowed(self) -> Self

If enabled, the router checks if another method is allowed for the current route, if the current request can not be routed. If this is the case, the request is answered with MethodNotAllowed and HTTP status code 405. If no other Method is allowed, the request is delegated to the NotFound handler.

Source

pub fn handle_options(self) -> Self

If enabled, the router automatically replies to OPTIONS requests. Custom OPTIONS handlers take priority over automatic replies.

Source

pub fn global_options(self, handler: impl Handler + 'static) -> Self

An optional handler that is called on automatic OPTIONS requests. The handler is only called if handle_options is true and no OPTIONS handler for the specific path was set. The Allowed header is set before calling the handler.

Source

pub fn not_found(self, handler: impl Handler + 'static) -> Self

Configurable handler which is called when no matching route is found.

Source

pub fn method_not_allowed(self, handler: impl Handler + 'static) -> Self

A configurable handler which is called when a request cannot be routed and handle_method_not_allowed is true. The Allow header with allowed request methods is set before the handler is called.

Source

pub fn allowed(&self, path: &'path str) -> Vec<&str>

Returns a list of the allowed methods for a specific path

use httprouter::Router;
use hyper::{Response, Body, Method};

let router = Router::default()
    .get("/home", |_| async {
        Ok(Response::new(Body::from("Welcome!")))
    })
    .post("/home", |_| async {
        Ok(Response::new(Body::from("Welcome!")))
    });

let allowed = router.allowed("/home");
assert!(allowed.contains(&"GET"));
assert!(allowed.contains(&"POST"));
assert!(allowed.contains(&"OPTIONS"));
Source§

impl<'path> Router<'path>

Source

pub fn into_service(self) -> MakeRouterService<'path>

Converts the Router into a Service which you can serve directly with Hyper. If you have an existing Service that you want to incorporate a Router into, see Router::serve.

// Our router...
let router = Router::default();

// Convert it into a service...
let service = router.into_service();

// Serve with hyper
hyper::Server::bind(&([127, 0, 0, 1], 3030).into())
    .serve(service)
    .await?;
Source

pub fn serve(&self, req: Request<Body>) -> ResponseFut

An asynchronous function from a Request to a Response. You will generally not need to use this function directly, and instead use Router::into_service. However, it may be useful when incorporating the router into a larger service.


let router = Arc::new(Router::default());

let make_svc = make_service_fn(move |_| {
    let router = router.clone();
    async move {
        Ok::<_, Infallible>(service_fn(move |req: Request<Body>| {
            let router = router.clone();
            async move { router.serve(req).await }
        }))
    }
});

let server = Server::bind(&([127, 0, 0, 1], 3000).into())
    .serve(make_svc)
    .await;

Trait Implementations§

Source§

impl Default for Router<'_>

The default httprouter configuration

Source§

fn default() -> Self

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

Auto Trait Implementations§

§

impl<'path> Freeze for Router<'path>

§

impl<'path> !RefUnwindSafe for Router<'path>

§

impl<'path> Send for Router<'path>

§

impl<'path> Sync for Router<'path>

§

impl<'path> Unpin for Router<'path>

§

impl<'path> !UnwindSafe for Router<'path>

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, 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<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