1
0
mirror of https://github.com/actix/actix-extras.git synced 2024-12-04 20:11:55 +01:00
actix-extras/examples/r2d2/src/main.rs

66 lines
1.7 KiB
Rust
Raw Normal View History

2018-02-16 08:05:10 +01:00
//! Actix web r2d2 example
extern crate serde;
extern crate serde_json;
extern crate uuid;
extern crate futures;
extern crate actix;
extern crate actix_web;
extern crate env_logger;
extern crate r2d2;
extern crate r2d2_sqlite;
extern crate rusqlite;
2018-03-31 03:54:38 +02:00
use actix::prelude::*;
use actix_web::{
2018-03-31 09:16:55 +02:00
middleware, http, server, App, AsyncResponder, HttpRequest, HttpResponse, Error};
2018-02-16 08:05:10 +01:00
use futures::future::Future;
use r2d2_sqlite::SqliteConnectionManager;
mod db;
use db::{CreateUser, DbExecutor};
/// State with DbExecutor address
struct State {
db: Addr<Syn, DbExecutor>,
}
/// Async request handler
fn index(req: HttpRequest<State>) -> Box<Future<Item=HttpResponse, Error=Error>> {
let name = &req.match_info()["name"];
req.state().db.send(CreateUser{name: name.to_owned()})
.from_err()
.and_then(|res| {
match res {
2018-03-31 08:37:15 +02:00
Ok(user) => Ok(HttpResponse::Ok().json(user)),
2018-03-31 03:54:38 +02:00
Err(_) => Ok(HttpResponse::InternalServerError().into())
2018-02-16 08:05:10 +01:00
}
})
.responder()
}
fn main() {
::std::env::set_var("RUST_LOG", "actix_web=debug");
2018-03-31 03:54:38 +02:00
env_logger::init();
2018-02-16 08:05:10 +01:00
let sys = actix::System::new("r2d2-example");
2018-02-16 18:42:15 +01:00
// r2d2 pool
2018-02-16 08:05:10 +01:00
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
2018-03-31 03:54:38 +02:00
let _ = server::new(move || {
2018-03-31 09:16:55 +02:00
App::with_state(State{db: addr.clone()})
2018-02-16 08:05:10 +01:00
// enable logger
.middleware(middleware::Logger::default())
2018-03-31 03:54:38 +02:00
.resource("/{name}", |r| r.method(http::Method::GET).a(index))})
2018-02-16 08:05:10 +01:00
.bind("127.0.0.1:8080").unwrap()
.start();
let _ = sys.run();
}