[][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>>; }
This is supported on feature="router" only.

A context extension. This extension must be used in Router, otherwise you cannot get expected router parameters.

Example

use roa::router::{Router, RouterParam};
use roa::{App, Context, Status};
use roa::http::StatusCode;
use roa::tcp::Listener;
use async_std::task::spawn;

async fn test(ctx: &mut Context) -> Result<(), Status> {
    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>>

This is supported on feature="router" only.

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

This is supported on feature="router" only.

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

Example

use roa::router::{Router, RouterParam};
use roa::{App, Context, Status};
use roa::http::StatusCode;
use roa::tcp::Listener;
use async_std::task::spawn;

async fn test(ctx: &mut Context) -> Result<(), Status> {
    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...

Implementors

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

Loading content...