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
|
|
|
|
2022-01-29 17:25:46 +01:00
|
|
|
use actix_web::{
|
|
|
|
error::InternalError, http::StatusCode, middleware, web, App, Error, HttpResponse,
|
|
|
|
HttpServer,
|
|
|
|
};
|
2019-03-06 19:04:41 +01:00
|
|
|
use r2d2::Pool;
|
2018-04-13 03:18:42 +02:00
|
|
|
use r2d2_sqlite::SqliteConnectionManager;
|
2019-03-06 19:04:41 +01:00
|
|
|
|
|
|
|
/// Async request handler. Ddb pool is stored in application state.
|
2019-12-07 18:59:24 +01:00
|
|
|
async fn index(
|
2019-03-07 23:50:29 +01:00
|
|
|
path: web::Path<String>,
|
2019-03-17 04:23:09 +01:00
|
|
|
db: web::Data<Pool<SqliteConnectionManager>>,
|
2019-12-07 18:59:24 +01:00
|
|
|
) -> Result<HttpResponse, Error> {
|
2019-03-06 19:04:41 +01:00
|
|
|
// execute sync code in threadpool
|
2019-12-07 18:59:24 +01:00
|
|
|
let res = 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)
|
2018-04-13 03:18:42 +02:00
|
|
|
})
|
2019-03-06 19:04:41 +01:00
|
|
|
})
|
2019-12-07 18:59:24 +01:00
|
|
|
.await
|
2022-01-29 17:25:46 +01:00
|
|
|
.unwrap()
|
2019-12-07 18:59:24 +01:00
|
|
|
.map(|user| HttpResponse::Ok().json(user))
|
2022-01-29 17:25:46 +01:00
|
|
|
.map_err(|e| InternalError::new(e, StatusCode::INTERNAL_SERVER_ERROR))?;
|
2019-12-07 18:59:24 +01:00
|
|
|
Ok(res)
|
2018-04-13 03:18:42 +02:00
|
|
|
}
|
|
|
|
|
2020-09-12 17:49:45 +02:00
|
|
|
#[actix_web::main]
|
2019-12-07 18:59:24 +01:00
|
|
|
async fn main() -> io::Result<()> {
|
2019-03-06 19:04:41 +01:00
|
|
|
std::env::set_var("RUST_LOG", "actix_web=debug");
|
2018-04-13 03:18:42 +02:00
|
|
|
env_logger::init();
|
|
|
|
|
|
|
|
// 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()
|
2022-01-29 17:25:46 +01:00
|
|
|
.app_data(web::Data::new(pool.clone())) // <- store db pool in app state
|
2019-03-26 04:29:00 +01:00
|
|
|
.wrap(middleware::Logger::default())
|
2019-12-07 18:59:24 +01:00
|
|
|
.route("/{name}", web::get().to(index))
|
2019-03-06 19:04:41 +01:00
|
|
|
})
|
|
|
|
.bind("127.0.0.1:8080")?
|
2019-12-25 17:48:33 +01:00
|
|
|
.run()
|
2019-12-07 18:59:24 +01:00
|
|
|
.await
|
2018-04-13 03:18:42 +02:00
|
|
|
}
|