const-router 0.1.0

Compile-time string-key router with Tower service integration.
Documentation

const-router

Version Documentation License

const-router is a small string-key router that can be built in a static. Routes are declared with a macro, sorted at compile time, and dispatched with a binary search. The router also implements tower::Service.

Features

  • router! builds a Router from static route keys and handlers.
  • #[handler] converts sync or async functions returning Result into router handlers.
  • ExtractKey lets request types choose the string used for routing.
  • The optional http feature implements ExtractKey for http::Request<T> using the URI path.

Example

use const_router::{handler, router, ExtractKey, Router};

#[derive(Debug)]
struct Request {
    path: &'static str,
}

impl ExtractKey for Request {
    fn extract_key(&self) -> &str {
        self.path
    }
}

#[handler]
fn home(_req: Request) -> Result<&'static str, &'static str> {
    Ok("home")
}

#[handler]
fn not_found() -> Result<&'static str, &'static str> {
    Ok("not found")
}

static ROUTER: Router<Request, &'static str, &'static str> = router! {
    not_found,
    "/" => home,
};

# async fn run() -> Result<(), &'static str> {
let response = ROUTER.handle(Request { path: "/" }).await?;
assert_eq!(response, "home");
# Ok(())
# }

Handler Functions

Handlers can be synchronous or asynchronous functions. They must return Result<TResponse, TError> and may take either zero arguments or one request argument.

# use const_router::handler;
# struct Request;
#[handler]
fn with_request(_req: Request) -> Result<&'static str, &'static str> {
    Ok("matched")
}

#[handler]
async fn async_without_request() -> Result<&'static str, &'static str> {
    Ok("fallback")
}

HTTP Requests

Enable the http feature to route http::Request<T> values by URI path.

[dependencies]
const-router = { version = "0.1", features = ["http"] }

License

Licensed under either of:

  • Apache License, Version 2.0
  • MIT license

at your option.