1
0
mirror of https://github.com/fafhrd91/actix-web synced 2025-01-18 22:01:50 +01:00

74 lines
2.0 KiB
Rust
Raw Normal View History

2017-12-18 16:25:26 -08:00
//! Actix web diesel example
//!
//! Diesel does not support tokio, so we have to run it in separate threads.
//! Actix supports sync actors by default, so we going to create sync actor that will
//! use diesel. Technically sync actors are worker style actors, multiple of them
2017-12-18 20:03:42 -08:00
//! can run in parallel and process messages from same queue.
2017-12-18 16:25:26 -08:00
extern crate serde;
extern crate serde_json;
#[macro_use]
extern crate serde_derive;
#[macro_use]
extern crate diesel;
extern crate uuid;
extern crate futures;
extern crate actix;
extern crate actix_web;
extern crate env_logger;
2017-12-31 08:12:26 +01:00
use actix::*;
2017-12-18 16:25:26 -08:00
use actix_web::*;
2017-12-31 08:12:26 +01:00
2017-12-18 16:25:26 -08:00
use diesel::prelude::*;
2017-12-20 16:32:31 -08:00
use futures::future::Future;
2017-12-18 16:25:26 -08:00
2017-12-20 17:43:43 -08:00
mod db;
2017-12-18 16:25:26 -08:00
mod models;
mod schema;
2017-12-20 17:43:43 -08:00
use db::{CreateUser, DbExecutor};
2017-12-18 16:30:35 -08:00
/// State with DbExecutor address
2017-12-18 16:25:26 -08:00
struct State {
2018-02-12 19:15:39 -08:00
db: Addr<Syn, DbExecutor>,
2017-12-18 16:25:26 -08:00
}
2017-12-18 16:30:35 -08:00
/// Async request handler
2017-12-18 16:25:26 -08:00
fn index(req: HttpRequest<State>) -> Box<Future<Item=HttpResponse, Error=Error>> {
let name = &req.match_info()["name"];
2018-02-12 23:13:06 -08:00
req.state().db.send(CreateUser{name: name.to_owned()})
2017-12-20 21:06:04 -08:00
.from_err()
.and_then(|res| {
match res {
Ok(user) => Ok(httpcodes::HTTPOk.build().json(user)?),
2017-12-31 20:08:35 -08:00
Err(_) => Ok(httpcodes::HTTPInternalServerError.into())
2017-12-20 21:06:04 -08:00
}
})
.responder()
2017-12-18 16:25:26 -08:00
}
fn main() {
::std::env::set_var("RUST_LOG", "actix_web=info");
let _ = env_logger::init();
let sys = actix::System::new("diesel-example");
// Start db executor actors
let addr = SyncArbiter::start(3, || {
DbExecutor(SqliteConnection::establish("test.db").unwrap())
});
// Start http server
2017-12-31 08:12:26 +01:00
let _addr = HttpServer::new(move || {
2017-12-18 16:25:26 -08:00
Application::with_state(State{db: addr.clone()})
// enable logger
2017-12-26 19:59:41 -08:00
.middleware(middleware::Logger::default())
2017-12-18 16:25:26 -08:00
.resource("/{name}", |r| r.method(Method::GET).a(index))})
.bind("127.0.0.1:8080").unwrap()
2017-12-19 09:08:36 -08:00
.start();
2017-12-18 16:25:26 -08:00
println!("Started http server: 127.0.0.1:8080");
let _ = sys.run();
}