[][src]Struct httprouter::router::Router

pub struct Router<K: Eq + Hash, V> {
    pub redirect_trailing_slash: bool,
    pub redirect_fixed_path: bool,
    pub handle_method_not_allowed: bool,
    pub handle_options: bool,
    pub global_options: Option<V>,
    pub not_found: Option<V>,
    pub method_not_allowed: Option<V>,
    // some fields omitted
}

Router is container which can be used to dispatch requests to different handlers via configurable routes.

Handlers (the value stored by the router) are indexed by keys. For example, the HyperRouter uses HTTP methods as keys. This leads to increased lookup performance.

Fields

redirect_trailing_slash: bool

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.

redirect_fixed_path: bool

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.

handle_method_not_allowed: bool

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.

handle_options: bool

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

global_options: Option<V>

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.

not_found: Option<V>

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

method_not_allowed: Option<V>

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.

Implementations

impl Router<Method, Box<dyn Handler + Send + Sync>>[src]

pub fn into_service(self) -> MakeRouterService[src]

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

// 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?;

pub fn serve(
    &self,
    req: Request<Body>
) -> Pin<Box<dyn Future<Output = Result<Response<Body>>> + Send + Sync>>
[src]

An asynchronous function from a Request to a Response. You will generally not need to use this function directly, and instead use MakeRouterService or RouterService. However, this may be useful in certain cases. For example, RouterService wraps the Router in an Arc which may introduce unneccesary overhead when using a single threaded runtime.


let mut router: HyperRouter = Router::default();

let router = Rc::new(router);
    
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())
    .executor(SingleThreadedExecutor)
    .serve(make_svc)
    .await;

impl<K: Eq + Hash, V> Router<K, V>[src]

pub fn handle(&mut self, path: &str, key: K, value: V)[src]

Insert a value into the router for a specific path indexed by a key.

use httprouter::Router;
use hyper::Method;

let mut router: Router<Method, String> = Router::default();
router.handle("/teapot", Method::GET, "I am a teapot".to_string());

pub fn lookup(
    &mut self,
    key: &K,
    path: &str
) -> Result<RouteLookup<'_, V>, bool>
[src]

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 http::Method;

let mut router = Router::default();
router.get("/home", "Welcome!");

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

pub fn serve_files()[src]

TODO

impl<V> Router<Method, V>[src]

pub fn get(&mut self, path: &str, handle: V)[src]

Register a handler for GET requests

pub fn head(&mut self, path: &str, handle: V)[src]

Register a handler for HEAD requests

pub fn options(&mut self, path: &str, handle: V)[src]

Register a handler for OPTIONS requests

pub fn post(&mut self, path: &str, handle: V)[src]

Register a handler for POST requests

pub fn put(&mut self, path: &str, handle: V)[src]

Register a handler for PUT requests

pub fn patch(&mut self, path: &str, handle: V)[src]

Register a handler for PATCH requests

pub fn delete(&mut self, path: &str, handle: V)[src]

Register a handler for DELETE requests

pub fn allowed(&self, path: &str) -> Vec<String>[src]

Returns a list of the allowed methods for a specific path

use httprouter::Router;
use http::Method;

let mut router = Router::default();
router.get("/products", "all products");
router.post("/products", "product created");

let allowed = router.allowed("/products");
assert!(allowed.contains(&"GET".to_string()));
assert!(allowed.contains(&"POST".to_string()));

Trait Implementations

impl<K: Eq + Hash, V> Default for Router<K, V>[src]

The default httprouter configuration

Auto Trait Implementations

impl<K, V> RefUnwindSafe for Router<K, V> where
    K: RefUnwindSafe,
    V: RefUnwindSafe
[src]

impl<K, V> Send for Router<K, V> where
    K: Send,
    V: Send
[src]

impl<K, V> Sync for Router<K, V> where
    K: Sync,
    V: Sync
[src]

impl<K, V> Unpin for Router<K, V> where
    K: Unpin,
    V: Unpin
[src]

impl<K, V> UnwindSafe for Router<K, V> where
    K: UnwindSafe,
    V: UnwindSafe
[src]

Blanket Implementations

impl<T> Any for T where
    T: 'static + ?Sized
[src]

impl<T> Borrow<T> for T where
    T: ?Sized
[src]

impl<T> BorrowMut<T> for T where
    T: ?Sized
[src]

impl<T> From<T> for T[src]

impl<T> Instrument for T[src]

impl<T> Instrument for T[src]

impl<T, U> Into<U> for T where
    U: From<T>, 
[src]

impl<T, U> TryFrom<U> for T where
    U: Into<T>, 
[src]

type Error = Infallible

The type returned in the event of a conversion error.

impl<T, U> TryInto<U> for T where
    U: TryFrom<T>, 
[src]

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

The type returned in the event of a conversion error.