Skip to main content

with_defaults

Function with_defaults 

Source
pub fn with_defaults(router: Router) -> Router
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}