[][src]Trait roa_router::RouterParam

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

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

Example

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

async fn test(ctx: &mut Context<()>) -> Result<(), Error> {
    let id: u64 = ctx.must_param("id")?.parse()?;
    assert_eq!(0, id);
    Ok(())
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let router = Router::new().on("/:id", test);
    let app = App::new(()).end(router.routes("user")?);
    let (addr, server) = app.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<'a>(&self, name: &'a str) -> Result<Variable<'a, String>>

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

fn param<'a>(&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, Context, Error};
use roa_core::http::StatusCode;
use roa_tcp::Listener;
use async_std::task::spawn;

async fn test(ctx: &mut Context<()>) -> Result<(), Error> {
    assert!(ctx.param("name").is_none());
    Ok(())
}

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

Loading content...

Implementations on Foreign Types

impl<S> RouterParam for Context<S>[src]

Loading content...

Implementors

Loading content...