1
0
mirror of https://github.com/actix/examples synced 2024-12-03 18:22:14 +01:00
examples/r2d2/src/main.rs

57 lines
1.6 KiB
Rust
Raw Normal View History

//! Actix web r2d2 example
2019-03-06 19:04:41 +01:00
use std::io;
2019-03-07 23:50:29 +01:00
use actix_web::{middleware, web, App, Error, HttpResponse, HttpServer};
2019-03-06 19:04:41 +01:00
use futures::Future;
use r2d2::Pool;
use r2d2_sqlite::SqliteConnectionManager;
2019-03-06 19:04:41 +01:00
use uuid;
/// Async request handler. Ddb pool is stored in application state.
fn index(
2019-03-07 23:50:29 +01:00
path: web::Path<String>,
db: web::State<Pool<SqliteConnectionManager>>,
2019-03-06 19:04:41 +01:00
) -> impl Future<Item = HttpResponse, Error = Error> {
// execute sync code in threadpool
2019-03-07 23:50:29 +01:00
web::block(move || {
2019-03-06 19:04:41 +01:00
let conn = db.get().unwrap();
let uuid = format!("{}", uuid::Uuid::new_v4());
conn.execute(
"INSERT INTO users (id, name) VALUES ($1, $2)",
&[&uuid, &path.into_inner()],
)
.unwrap();
conn.query_row("SELECT name FROM users WHERE id=$1", &[&uuid], |row| {
row.get::<_, String>(0)
})
2019-03-06 19:04:41 +01:00
})
.then(|res| match res {
Ok(user) => Ok(HttpResponse::Ok().json(user)),
Err(_) => Ok(HttpResponse::InternalServerError().into()),
})
}
2019-03-06 19:04:41 +01:00
fn main() -> io::Result<()> {
std::env::set_var("RUST_LOG", "actix_web=debug");
env_logger::init();
2019-03-06 19:04:41 +01:00
let sys = actix_rt::System::new("r2d2-example");
// r2d2 pool
let manager = SqliteConnectionManager::file("test.db");
let pool = r2d2::Pool::new(manager).unwrap();
2019-03-06 19:04:41 +01:00
// start http server
HttpServer::new(move || {
App::new()
.state(pool.clone()) // <- store db pool in app state
2019-03-07 04:45:45 +01:00
.middleware(middleware::Logger::default())
2019-03-07 00:51:56 +01:00
.route("/{name}", web::get().to_async(index))
2019-03-06 19:04:41 +01:00
})
.bind("127.0.0.1:8080")?
.start();
2019-03-06 19:29:01 +01:00
sys.run()
}