pub mod macros;
pub mod router;
pub mod trie;
use crate::context::Context;
use crate::error::Result;
pub use router::Router;
use std::future::Future;
use std::pin::Pin;
pub type RouteHandler =
for<'a> fn(&'a mut Context) -> Pin<Box<dyn Future<Output = Result<()>> + Send + 'a>>;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BeforeAction {
Continue,
Stop,
}
pub type BeforeFn =
for<'a> fn(&'a mut Context) -> Pin<Box<dyn Future<Output = Result<BeforeAction>> + Send + 'a>>;
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct SocketOptions {
pub json: bool,
pub max_message_size: Option<usize>,
}
pub struct Route {
pub method: String,
pub path: String,
pub handler: RouteHandler,
pub xhr_only: bool,
pub before: Option<BeforeFn>,
pub socket: Option<SocketOptions>,
}
impl Route {
pub fn new(method: &str, path: &str, handler: RouteHandler) -> Self {
Self {
method: method.to_string(),
path: path.to_string(),
handler,
xhr_only: false,
before: None,
socket: None,
}
}
pub fn get(path: &str, handler: RouteHandler) -> Self {
Self::new("GET", path, handler)
}
pub fn post(path: &str, handler: RouteHandler) -> Self {
Self::new("POST", path, handler)
}
pub fn put(path: &str, handler: RouteHandler) -> Self {
Self::new("PUT", path, handler)
}
pub fn delete(path: &str, handler: RouteHandler) -> Self {
Self::new("DELETE", path, handler)
}
pub fn xhr(path: &str, handler: RouteHandler) -> Self {
Self {
method: "XHR".to_string(),
path: path.to_string(),
handler,
xhr_only: true,
before: None,
socket: None,
}
}
#[cfg(feature = "websocket")]
pub fn websocket(path: &str, handler: RouteHandler) -> Self {
Self {
method: "GET".to_string(),
path: path.to_string(),
handler,
xhr_only: false,
before: None,
socket: Some(SocketOptions::default()),
}
}
#[cfg(feature = "websocket")]
pub fn websocket_with(path: &str, handler: RouteHandler, socket: SocketOptions) -> Self {
Self {
socket: Some(socket),
..Self::websocket(path, handler)
}
}
}
#[macro_export]
macro_rules! routes {
(@sockflag $options:ident,) => {};
(@sockflag $options:ident, json) => {
$options.json = true;
};
(@sockflag $options:ident, json, $($rest:tt)*) => {
$options.json = true;
$crate::routes!(@sockflag $options, $($rest)*);
};
(@sockflag $options:ident, text) => {
$options.json = false;
};
(@sockflag $options:ident, text, $($rest:tt)*) => {
$options.json = false;
$crate::routes!(@sockflag $options, $($rest)*);
};
(@sockflag $options:ident, max = $size:expr) => {
$options.max_message_size = Some($size);
};
(@sockflag $options:ident, max = $size:expr, $($rest:tt)*) => {
$options.max_message_size = Some($size);
$crate::routes!(@sockflag $options, $($rest)*);
};
(@socket $path:expr, $handler:expr, [$($flags:tt)*]) => {{
#[allow(unused_mut)]
let mut __options = $crate::routing::SocketOptions::default();
$crate::routes!(@sockflag __options, $($flags)*);
$crate::routing::Route::websocket_with(
$path,
|ctx| Box::pin(async { $handler(ctx).await }),
__options
)
}};
(@xhr $path:expr, $handler:expr) => {
$crate::routing::Route::xhr(
$path,
|ctx| Box::pin(async { $handler(ctx).await })
)
};
(@plain $method:ident, $path:expr, $handler:expr) => {
$crate::routing::Route::new(
stringify!($method),
$path,
|ctx| Box::pin(async { $handler(ctx).await })
)
};
(@munch $out:ident,) => {};
(@munch $out:ident, SOCKET $path:literal => $handler:expr, [$($flags:tt)*], $($rest:tt)*) => {
$out.push($crate::routes!(@socket $path, $handler, [$($flags)*]));
$crate::routes!(@munch $out, $($rest)*);
};
(@munch $out:ident, SOCKET $path:literal => $handler:expr, [$($flags:tt)*]) => {
$out.push($crate::routes!(@socket $path, $handler, [$($flags)*]));
};
(@munch $out:ident, SOCKET $path:literal => $handler:expr, $($rest:tt)*) => {
$out.push($crate::routes!(@socket $path, $handler, []));
$crate::routes!(@munch $out, $($rest)*);
};
(@munch $out:ident, SOCKET $path:literal => $handler:expr) => {
$out.push($crate::routes!(@socket $path, $handler, []));
};
(@munch $out:ident, XHR $path:literal => $handler:expr, $($rest:tt)*) => {
$out.push($crate::routes!(@xhr $path, $handler));
$crate::routes!(@munch $out, $($rest)*);
};
(@munch $out:ident, XHR $path:literal => $handler:expr) => {
$out.push($crate::routes!(@xhr $path, $handler));
};
(@munch $out:ident, $method:ident $path:literal => $handler:expr, $($rest:tt)*) => {
$out.push($crate::routes!(@plain $method, $path, $handler));
$crate::routes!(@munch $out, $($rest)*);
};
(@munch $out:ident, $method:ident $path:literal => $handler:expr) => {
$out.push($crate::routes!(@plain $method, $path, $handler));
};
(before: $before:expr, $($rest:tt)*) => {{
let __before_fn: $crate::routing::BeforeFn =
|ctx| Box::pin(async move { $before(ctx).await });
#[allow(unused_mut)]
let mut __routes: Vec<$crate::routing::Route> = Vec::new();
$crate::routes!(@munch __routes, $($rest)*);
for __r in &mut __routes {
__r.before = Some(__before_fn);
}
__routes
}};
($($rest:tt)*) => {{
#[allow(unused_mut)]
let mut __routes: Vec<$crate::routing::Route> = Vec::new();
$crate::routes!(@munch __routes, $($rest)*);
__routes
}};
}
#[cfg(test)]
mod tests {
use super::*;
use crate::context::Context;
async fn dummy(_ctx: &mut Context) -> Result<()> {
Ok(())
}
async fn dummy_before(_ctx: &mut Context) -> Result<BeforeAction> {
Ok(BeforeAction::Continue)
}
#[test]
fn routes_macro_without_before_leaves_field_none() {
let routes = routes![
GET "/" => dummy,
POST "/items" => dummy,
];
assert_eq!(routes.len(), 2);
for r in &routes {
assert!(
r.before.is_none(),
"bare routes! arm must leave Route::before as None"
);
}
}
#[test]
fn routes_macro_with_before_sets_field_on_every_route() {
let routes = routes![
before: dummy_before,
GET "/" => dummy,
POST "/items" => dummy,
DELETE "/items/{id}" => dummy,
];
assert_eq!(routes.len(), 3);
for r in &routes {
assert!(
r.before.is_some(),
"routes! with `before:` clause must set Route::before on every route"
);
}
}
}