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

58 lines
1.6 KiB
Rust
Raw Normal View History

//! Actix web r2d2 example
2019-03-06 19:04:41 +01:00
use std::io;
use actix_web::{
error::InternalError, http::StatusCode, middleware, web, App, Error, HttpResponse,
HttpServer,
};
2019-03-06 19:04:41 +01:00
use r2d2::Pool;
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)
})
2019-03-06 19:04:41 +01:00
})
2019-12-07 18:59:24 +01:00
.await
.unwrap()
2019-12-07 18:59:24 +01:00
.map(|user| HttpResponse::Ok().json(user))
.map_err(|e| InternalError::new(e, StatusCode::INTERNAL_SERVER_ERROR))?;
2019-12-07 18:59:24 +01:00
Ok(res)
}
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");
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()
.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
}