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

69 lines
1.7 KiB
Rust
Raw Normal View History

//! Actix web r2d2 example
extern crate actix;
extern crate actix_web;
extern crate env_logger;
2018-05-08 20:08:43 +02:00
extern crate futures;
extern crate r2d2;
extern crate r2d2_sqlite;
extern crate rusqlite;
2018-05-08 20:08:43 +02:00
extern crate serde;
extern crate serde_json;
extern crate uuid;
use actix::prelude::*;
2018-05-21 06:03:29 +02:00
use actix_web::{
http, middleware, server, App, AsyncResponder, Error, HttpRequest, HttpResponse,
};
use futures::future::Future;
use r2d2_sqlite::SqliteConnectionManager;
mod db;
use db::{CreateUser, DbExecutor};
/// State with DbExecutor address
struct State {
2018-07-16 08:36:53 +02:00
db: Addr<DbExecutor>,
}
/// Async request handler
2018-07-16 08:36:53 +02:00
fn index(req: &HttpRequest<State>) -> Box<Future<Item = HttpResponse, Error = Error>> {
let name = &req.match_info()["name"];
2018-05-08 20:08:43 +02:00
req.state()
.db
.send(CreateUser {
name: name.to_owned(),
})
.from_err()
2018-05-08 20:08:43 +02:00
.and_then(|res| match res {
Ok(user) => Ok(HttpResponse::Ok().json(user)),
Err(_) => Ok(HttpResponse::InternalServerError().into()),
})
.responder()
}
fn main() {
::std::env::set_var("RUST_LOG", "actix_web=debug");
env_logger::init();
let sys = actix::System::new("r2d2-example");
// r2d2 pool
let manager = SqliteConnectionManager::file("test.db");
let pool = r2d2::Pool::new(manager).unwrap();
// Start db executor actors
let addr = SyncArbiter::start(3, move || DbExecutor(pool.clone()));
// Start http server
server::new(move || {
App::with_state(State{db: addr.clone()})
// enable logger
.middleware(middleware::Logger::default())
2018-05-08 20:08:43 +02:00
.resource("/{name}", |r| r.method(http::Method::GET).a(index))
}).bind("127.0.0.1:8080")
.unwrap()
.start();
let _ = sys.run();
}