[]Trait roa::preload::RouterParam

pub trait RouterParam {
    fn must_param(&self, name: &'a str) -> Result<Variable<'a, String>, Error>;
fn param(&self, name: &'a str) -> Option<Variable<'a, String>>; }

A context extension. This extension must be used in downstream of middleware RouteEndpoint, otherwise you cannot get expected router parameter.

Example

use roa_router::{Router, RouterParam};
use roa_core::App;
use roa_core::http::StatusCode;
use roa_tcp::Listener;
use async_std::task::spawn;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let mut router = Router::<()>::new();
    router.get("/:id", |ctx| async move {
        let id: u64 = ctx.must_param("id")?.parse()?;
        assert_eq!(0, id);
        Ok(())
    });
    let (addr, server) = App::new(())
        .gate(router.routes("/user")?)
        .run()?;
    spawn(server);
    let resp = reqwest::get(&format!("http://{}/user/0", addr)).await?;
    assert_eq!(StatusCode::OK, resp.status());
    Ok(())
}

Required methods

fn must_param(&self, name: &'a str) -> Result<Variable<'a, String>, Error>

Must get a router parameter, throw 500 INTERNAL SERVER ERROR if it not exists.

fn param(&self, name: &'a str) -> Option<Variable<'a, String>>

Try to get a router parameter, return None if it not exists.

Example

use roa_router::{Router, RouterParam};
use roa_core::App;
use roa_core::http::StatusCode;
use roa_tcp::Listener;
use async_std::task::spawn;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let mut router = Router::<()>::new();
    router.get("/:id", |ctx| async move {
        assert!(ctx.param("name").is_none());
        Ok(())
    });
    let (addr, server) = App::new(())
        .gate(router.routes("/user")?)
        .run()?;
    spawn(server);
    let resp = reqwest::get(&format!("http://{}/user/0", addr)).await?;
    assert_eq!(StatusCode::OK, resp.status());
    Ok(())
}

Loading content...

Implementors

impl<S> RouterParam for Context<S> where
    S: State

Loading content...