obsidian-rs / obsidian

Ergonomic async http framework for reliable and efficient web
MIT License
26 stars 4 forks source link

Set Application State which is shared globally with all routes #44

Closed jk-gan closed 4 years ago

jk-gan commented 4 years ago

Currently, there is no simple way to share app states in Obsidian. App state can be a database client, connection pool and etc.

Simple suggestion(not final!):

#[tokio::main]
async fn obsidian_run(db: Database) {
    let mut app = App::new();

    // here to inject App State
    app.inject("db", db);

    let addr = ([127, 0, 0, 1], 3000).into();

    app.get("/", |_ctx| async { "Hello World" });
    app.get("/user", get_user);

    app.listen(&addr, || {
        println!("server is listening to {}", &addr);
    })
    .await;
}

// Handler
async fn get_user(ctx: Context) -> impl Responder {
    let db = ctx.get_state("db");
    // database query here
    Response::ok().json(user)
}
plwai commented 4 years ago

If possible, I prefer a way which can check for errors while doing compilation. So far I don't have the idea of implementation for it.