mirror of
https://github.com/actix/examples
synced 2025-06-28 09:50:36 +02:00
Restructure folders (#411)
This commit is contained in:
committed by
GitHub
parent
9db98162b2
commit
c3407627d0
15
database_interactions/r2d2/Cargo.toml
Normal file
15
database_interactions/r2d2/Cargo.toml
Normal file
@ -0,0 +1,15 @@
|
||||
[package]
|
||||
name = "r2d2-example"
|
||||
version = "1.0.0"
|
||||
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
||||
edition = "2018"
|
||||
|
||||
[dependencies]
|
||||
actix-web = "3"
|
||||
|
||||
env_logger = "0.8"
|
||||
uuid = { version = "0.8", features = ["v4"] }
|
||||
|
||||
r2d2 = "0.8"
|
||||
r2d2_sqlite = "0.14"
|
||||
rusqlite = "0.21"
|
53
database_interactions/r2d2/src/main.rs
Normal file
53
database_interactions/r2d2/src/main.rs
Normal file
@ -0,0 +1,53 @@
|
||||
//! Actix web r2d2 example
|
||||
use std::io;
|
||||
|
||||
use actix_web::{middleware, web, App, Error, HttpResponse, HttpServer};
|
||||
use r2d2::Pool;
|
||||
use r2d2_sqlite::SqliteConnectionManager;
|
||||
|
||||
/// Async request handler. Ddb pool is stored in application state.
|
||||
async fn index(
|
||||
path: web::Path<String>,
|
||||
db: web::Data<Pool<SqliteConnectionManager>>,
|
||||
) -> Result<HttpResponse, Error> {
|
||||
// execute sync code in threadpool
|
||||
let res = web::block(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)
|
||||
})
|
||||
})
|
||||
.await
|
||||
.map(|user| HttpResponse::Ok().json(user))
|
||||
.map_err(|_| HttpResponse::InternalServerError())?;
|
||||
Ok(res)
|
||||
}
|
||||
|
||||
#[actix_web::main]
|
||||
async fn main() -> io::Result<()> {
|
||||
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();
|
||||
|
||||
// start http server
|
||||
HttpServer::new(move || {
|
||||
App::new()
|
||||
.data(pool.clone()) // <- store db pool in app state
|
||||
.wrap(middleware::Logger::default())
|
||||
.route("/{name}", web::get().to(index))
|
||||
})
|
||||
.bind("127.0.0.1:8080")?
|
||||
.run()
|
||||
.await
|
||||
}
|
Reference in New Issue
Block a user