2018-04-13 03:18:42 +02:00
|
|
|
//! Actix web r2d2 example
|
2019-03-06 19:04:41 +01:00
|
|
|
use std::io;
|
2018-04-13 03:18:42 +02:00
|
|
|
|
2018-05-21 06:03:29 +02:00
|
|
|
use actix_web::{
|
2019-03-07 04:45:45 +01:00
|
|
|
blocking, extract::Path, middleware, web, App, Error, HttpResponse, HttpServer,
|
|
|
|
State,
|
2018-05-21 06:03:29 +02:00
|
|
|
};
|
2019-03-06 19:04:41 +01:00
|
|
|
use futures::Future;
|
|
|
|
use r2d2::Pool;
|
2018-04-13 03:18:42 +02:00
|
|
|
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(
|
|
|
|
path: Path<String>,
|
|
|
|
db: State<Pool<SqliteConnectionManager>>,
|
|
|
|
) -> impl Future<Item = HttpResponse, Error = Error> {
|
|
|
|
// execute sync code in threadpool
|
|
|
|
blocking::run(move || {
|
|
|
|
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)
|
2018-04-13 03:18:42 +02:00
|
|
|
})
|
2019-03-06 19:04:41 +01:00
|
|
|
})
|
|
|
|
.then(|res| match res {
|
|
|
|
Ok(user) => Ok(HttpResponse::Ok().json(user)),
|
|
|
|
Err(_) => Ok(HttpResponse::InternalServerError().into()),
|
|
|
|
})
|
2018-04-13 03:18:42 +02:00
|
|
|
}
|
|
|
|
|
2019-03-06 19:04:41 +01:00
|
|
|
fn main() -> io::Result<()> {
|
|
|
|
std::env::set_var("RUST_LOG", "actix_web=debug");
|
2018-04-13 03:18:42 +02:00
|
|
|
env_logger::init();
|
2019-03-06 19:04:41 +01:00
|
|
|
let sys = actix_rt::System::new("r2d2-example");
|
2018-04-13 03:18:42 +02:00
|
|
|
|
|
|
|
// 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();
|
2018-04-13 03:18:42 +02:00
|
|
|
|
2019-03-06 19:29:01 +01:00
|
|
|
sys.run()
|
2018-04-13 03:18:42 +02:00
|
|
|
}
|