Skip to main content

Router

Struct Router 

Source
pub struct Router { /* private fields */ }

Implementations§

Source§

impl Router

Source

pub fn new() -> Self

Examples found in repository?
examples/admin_demo.rs (line 67)
38async fn main() -> std::io::Result<()> {
39    let db = Db::memory().await.expect("db connect");
40    db.execute(
41        "CREATE TABLE users (
42            id INTEGER PRIMARY KEY AUTOINCREMENT,
43            name TEXT NOT NULL,
44            is_admin INTEGER NOT NULL
45        )",
46    )
47    .await
48    .expect("create schema");
49
50    User {
51        id: 0,
52        name: "Alice".into(),
53        is_admin: false,
54    }
55    .create(&db)
56    .await
57    .expect("seed alice");
58    User {
59        id: 0,
60        name: "Bob".into(),
61        is_admin: true,
62    }
63    .create(&db)
64    .await
65    .expect("seed bob");
66
67    let router = with_defaults(Router::new()).wrap(authenticate);
68    let router = admin::register::<User>(router, &db);
69
70    let addr: SocketAddr = ([127, 0, 0, 1], 3000).into();
71    eprintln!("admin demo: hit /admin/users with `Authorization: Bearer dev-admin` header");
72    Server::bind(addr).serve_router(router).await
73}
More examples
Hide additional examples
examples/homepage.rs (line 52)
50async fn main() -> std::io::Result<()> {
51    let addr: SocketAddr = ([127, 0, 0, 1], 3000).into();
52    let router = with_defaults(Router::new())
53        .get("/whoami", |req, _params| async move {
54            let id = req
55                .ctx()
56                .get::<RequestId>()
57                .map(|r| r.0.to_string())
58                .unwrap_or_else(|| "unknown".into());
59            Ok::<Response, Error>(text(format!("your request id is req-{id}\n")))
60        })
61        .get("/me", |req, _params| async move {
62            let id = require_auth(req.ctx())?;
63            Ok::<Response, Error>(text(format!("hello {}\n", id.user_id)))
64        })
65        .get("/admin-only", |req, _params| async move {
66            let id = require_admin(req.ctx())?;
67            Ok::<Response, Error>(text(format!("hello admin {}\n", id.user_id)))
68        })
69        .get("/crash", |_req, _params| async {
70            Err::<Response, Error>(Error::Internal("simulated failure".into()))
71        })
72        .get("/unauth", |_req, _params| async {
73            Err::<Response, Error>(Error::Unauthorized)
74        })
75        .wrap(request_id)
76        .wrap(authenticate)
77        .wrap(logger);
78    Server::bind(addr).serve_router(router).await
79}
Source

pub fn wrap<F, Fut>(self, middleware: F) -> Self
where F: Fn(Request, Next) -> Fut + Send + Sync + 'static, Fut: Future<Output = Result<Response, Error>> + Send + 'static,

Examples found in repository?
examples/admin_demo.rs (line 67)
38async fn main() -> std::io::Result<()> {
39    let db = Db::memory().await.expect("db connect");
40    db.execute(
41        "CREATE TABLE users (
42            id INTEGER PRIMARY KEY AUTOINCREMENT,
43            name TEXT NOT NULL,
44            is_admin INTEGER NOT NULL
45        )",
46    )
47    .await
48    .expect("create schema");
49
50    User {
51        id: 0,
52        name: "Alice".into(),
53        is_admin: false,
54    }
55    .create(&db)
56    .await
57    .expect("seed alice");
58    User {
59        id: 0,
60        name: "Bob".into(),
61        is_admin: true,
62    }
63    .create(&db)
64    .await
65    .expect("seed bob");
66
67    let router = with_defaults(Router::new()).wrap(authenticate);
68    let router = admin::register::<User>(router, &db);
69
70    let addr: SocketAddr = ([127, 0, 0, 1], 3000).into();
71    eprintln!("admin demo: hit /admin/users with `Authorization: Bearer dev-admin` header");
72    Server::bind(addr).serve_router(router).await
73}
More examples
Hide additional examples
examples/homepage.rs (line 75)
50async fn main() -> std::io::Result<()> {
51    let addr: SocketAddr = ([127, 0, 0, 1], 3000).into();
52    let router = with_defaults(Router::new())
53        .get("/whoami", |req, _params| async move {
54            let id = req
55                .ctx()
56                .get::<RequestId>()
57                .map(|r| r.0.to_string())
58                .unwrap_or_else(|| "unknown".into());
59            Ok::<Response, Error>(text(format!("your request id is req-{id}\n")))
60        })
61        .get("/me", |req, _params| async move {
62            let id = require_auth(req.ctx())?;
63            Ok::<Response, Error>(text(format!("hello {}\n", id.user_id)))
64        })
65        .get("/admin-only", |req, _params| async move {
66            let id = require_admin(req.ctx())?;
67            Ok::<Response, Error>(text(format!("hello admin {}\n", id.user_id)))
68        })
69        .get("/crash", |_req, _params| async {
70            Err::<Response, Error>(Error::Internal("simulated failure".into()))
71        })
72        .get("/unauth", |_req, _params| async {
73            Err::<Response, Error>(Error::Unauthorized)
74        })
75        .wrap(request_id)
76        .wrap(authenticate)
77        .wrap(logger);
78    Server::bind(addr).serve_router(router).await
79}
Source

pub fn get<F, Fut>(self, path: &str, handler: F) -> Self
where F: Fn(Request, Params) -> Fut + Send + Sync + 'static, Fut: Future<Output = Result<Response, Error>> + Send + 'static,

Examples found in repository?
examples/homepage.rs (lines 53-60)
50async fn main() -> std::io::Result<()> {
51    let addr: SocketAddr = ([127, 0, 0, 1], 3000).into();
52    let router = with_defaults(Router::new())
53        .get("/whoami", |req, _params| async move {
54            let id = req
55                .ctx()
56                .get::<RequestId>()
57                .map(|r| r.0.to_string())
58                .unwrap_or_else(|| "unknown".into());
59            Ok::<Response, Error>(text(format!("your request id is req-{id}\n")))
60        })
61        .get("/me", |req, _params| async move {
62            let id = require_auth(req.ctx())?;
63            Ok::<Response, Error>(text(format!("hello {}\n", id.user_id)))
64        })
65        .get("/admin-only", |req, _params| async move {
66            let id = require_admin(req.ctx())?;
67            Ok::<Response, Error>(text(format!("hello admin {}\n", id.user_id)))
68        })
69        .get("/crash", |_req, _params| async {
70            Err::<Response, Error>(Error::Internal("simulated failure".into()))
71        })
72        .get("/unauth", |_req, _params| async {
73            Err::<Response, Error>(Error::Unauthorized)
74        })
75        .wrap(request_id)
76        .wrap(authenticate)
77        .wrap(logger);
78    Server::bind(addr).serve_router(router).await
79}
Source

pub fn post<F, Fut>(self, path: &str, handler: F) -> Self
where F: Fn(Request, Params) -> Fut + Send + Sync + 'static, Fut: Future<Output = Result<Response, Error>> + Send + 'static,

Source

pub async fn dispatch(&self, req: Request) -> Response

Trait Implementations§

Source§

impl Default for Router

Source§

fn default() -> Self

Returns the “default value” for a type. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more