1
0
mirror of https://github.com/actix/examples synced 2024-11-23 22:41:07 +01:00

upgrade diesel, r2d2, state examples

This commit is contained in:
Nikolay Kim 2019-03-07 14:50:29 -08:00
parent 60a9df8abd
commit f39a53ea3a
10 changed files with 185 additions and 282 deletions

View File

@ -11,9 +11,7 @@ This project illustrates two examples:
*/ */
use std::io; use std::io;
use actix_web::{ use actix_web::{middleware, web, App, Error as AWError, HttpResponse, HttpServer};
middleware, web, App, Error as AWError, HttpResponse, HttpServer, State,
};
use futures::future::{join_all, ok as fut_ok, Future}; use futures::future::{join_all, ok as fut_ok, Future};
use r2d2_sqlite; use r2d2_sqlite;
use r2d2_sqlite::SqliteConnectionManager; use r2d2_sqlite::SqliteConnectionManager;
@ -23,7 +21,7 @@ use db::{Pool, Queries, WeatherAgg};
/// Version 1: Calls 4 queries in sequential order, as an asynchronous handler /// Version 1: Calls 4 queries in sequential order, as an asynchronous handler
fn asyncio_weather( fn asyncio_weather(
db: State<Pool>, db: web::State<Pool>,
) -> impl Future<Item = HttpResponse, Error = AWError> { ) -> impl Future<Item = HttpResponse, Error = AWError> {
let mut result: Vec<Vec<WeatherAgg>> = vec![]; let mut result: Vec<Vec<WeatherAgg>> = vec![];
@ -54,7 +52,7 @@ fn asyncio_weather(
/// Version 2: Calls 4 queries in parallel, as an asynchronous handler /// Version 2: Calls 4 queries in parallel, as an asynchronous handler
/// Returning Error types turn into None values in the response /// Returning Error types turn into None values in the response
fn parallel_weather( fn parallel_weather(
db: State<Pool>, db: web::State<Pool>,
) -> impl Future<Item = HttpResponse, Error = AWError> { ) -> impl Future<Item = HttpResponse, Error = AWError> {
let fut_result = vec![ let fut_result = vec![
Box::new(db::execute(&db, Queries::GetTopTenHottestYears)), Box::new(db::execute(&db, Queries::GetTopTenHottestYears)),

View File

@ -1,8 +1,10 @@
#[macro_use]
extern crate actix_web;
use std::{env, io}; use std::{env, io};
use actix_files as fs; use actix_files as fs;
use actix_session::{CookieSession, Session}; use actix_session::{CookieSession, Session};
use actix_web::extract::Path;
use actix_web::http::{header, Method, StatusCode}; use actix_web::http::{header, Method, StatusCode};
use actix_web::{ use actix_web::{
error, guard, middleware, web, App, Error, HttpRequest, HttpResponse, HttpServer, error, guard, middleware, web, App, Error, HttpRequest, HttpResponse, HttpServer,
@ -13,11 +15,13 @@ use futures::unsync::mpsc;
use futures::{future::ok, Future, Stream}; use futures::{future::ok, Future, Stream};
/// favicon handler /// favicon handler
#[get("/favicon")]
fn favicon() -> Result<fs::NamedFile> { fn favicon() -> Result<fs::NamedFile> {
Ok(fs::NamedFile::open("static/favicon.ico")?) Ok(fs::NamedFile::open("static/favicon.ico")?)
} }
/// simple index handler /// simple index handler
#[get("/welcome")]
fn welcome(session: Session, req: HttpRequest) -> Result<HttpResponse> { fn welcome(session: Session, req: HttpRequest) -> Result<HttpResponse> {
println!("{:?}", req); println!("{:?}", req);
@ -52,7 +56,7 @@ fn index_async(req: HttpRequest) -> impl Future<Item = HttpResponse, Error = Err
} }
/// async body /// async body
fn index_async_body(path: Path<String>) -> HttpResponse { fn index_async_body(path: web::Path<String>) -> HttpResponse {
let text = format!("Hello {}!", *path); let text = format!("Hello {}!", *path);
let (tx, rx_body) = mpsc::unbounded(); let (tx, rx_body) = mpsc::unbounded();
@ -63,7 +67,7 @@ fn index_async_body(path: Path<String>) -> HttpResponse {
} }
/// handler with path parameters like `/user/{name}/` /// handler with path parameters like `/user/{name}/`
fn with_param(req: HttpRequest, path: Path<(String,)>) -> HttpResponse { fn with_param(req: HttpRequest, path: web::Path<(String,)>) -> HttpResponse {
println!("{:?}", req); println!("{:?}", req);
HttpResponse::Ok() HttpResponse::Ok()
@ -84,9 +88,9 @@ fn main() -> io::Result<()> {
// cookie session middleware // cookie session middleware
.middleware(CookieSession::signed(&[0; 32]).secure(false)) .middleware(CookieSession::signed(&[0; 32]).secure(false))
// register favicon // register favicon
.service(web::resource("/favicon").to(favicon)) .service(favicon)
// register simple route, handle all methods // register simple route, handle all methods
.service(web::resource("/welcome").to(welcome)) .service(welcome)
// with path parameters // with path parameters
.service(web::resource("/user/{name}").route(web::get().to(with_param))) .service(web::resource("/user/{name}").route(web::get().to(with_param)))
// async handler // async handler

View File

@ -2,15 +2,14 @@
name = "diesel-example" name = "diesel-example"
version = "0.1.0" version = "0.1.0"
authors = ["Nikolay Kim <fafhrd91@gmail.com>"] authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
workspace = "../" workspace = ".."
edition = "2018"
[dependencies] [dependencies]
actix-web = { git="https://github.com/actix/actix-web.git", branch = "1.0" }
bytes = "0.4" bytes = "0.4"
env_logger = "0.5" env_logger = "0.6"
actix = "0.7"
actix-web = "0.7"
futures = "0.1" futures = "0.1"
uuid = { version = "0.5", features = ["serde", "v4"] } uuid = { version = "0.5", features = ["serde", "v4"] }
serde = "1.0" serde = "1.0"

View File

@ -1,55 +0,0 @@
//! Db executor actor
use actix::prelude::*;
use actix_web::*;
use diesel;
use diesel::prelude::*;
use diesel::r2d2::{ConnectionManager, Pool};
use uuid;
use models;
use schema;
/// This is db executor actor. We are going to run 3 of them in parallel.
pub struct DbExecutor(pub Pool<ConnectionManager<SqliteConnection>>);
/// This is only message that this actor can handle, but it is easy to extend
/// number of messages.
pub struct CreateUser {
pub name: String,
}
impl Message for CreateUser {
type Result = Result<models::User, Error>;
}
impl Actor for DbExecutor {
type Context = SyncContext<Self>;
}
impl Handler<CreateUser> for DbExecutor {
type Result = Result<models::User, Error>;
fn handle(&mut self, msg: CreateUser, _: &mut Self::Context) -> Self::Result {
use self::schema::users::dsl::*;
let uuid = format!("{}", uuid::Uuid::new_v4());
let new_user = models::NewUser {
id: &uuid,
name: &msg.name,
};
let conn: &SqliteConnection = &self.0.get().unwrap();
diesel::insert_into(users)
.values(&new_user)
.execute(conn)
.map_err(|_| error::ErrorInternalServerError("Error inserting person"))?;
let mut items = users
.filter(id.eq(&uuid))
.load::<models::User>(conn)
.map_err(|_| error::ErrorInternalServerError("Error loading person"))?;
Ok(items.pop().unwrap())
}
}

View File

@ -4,77 +4,74 @@
//! Actix supports sync actors by default, so we going to create sync actor //! Actix supports sync actors by default, so we going to create sync actor
//! that use diesel. Technically sync actors are worker style actors, multiple //! that use diesel. Technically sync actors are worker style actors, multiple
//! of them can run in parallel and process messages from same queue. //! of them can run in parallel and process messages from same queue.
extern crate serde;
extern crate serde_json;
#[macro_use]
extern crate serde_derive;
#[macro_use] #[macro_use]
extern crate diesel; extern crate diesel;
extern crate actix; #[macro_use]
extern crate actix_web; extern crate serde_derive;
extern crate env_logger;
extern crate futures;
extern crate r2d2;
extern crate uuid;
extern crate bytes;
// extern crate json;
use bytes::BytesMut;
use actix::prelude::*;
use actix_web::{
http, middleware, server, App, AsyncResponder, FutureResponse, HttpResponse, Path, Error, HttpRequest,
State, HttpMessage, error, Json
};
use actix_web::{error, middleware, web, App, Error, HttpResponse, HttpServer};
use bytes::{Bytes, BytesMut};
use diesel::prelude::*; use diesel::prelude::*;
use diesel::r2d2::ConnectionManager; use diesel::r2d2::{self, ConnectionManager};
use futures::{future, Future, Stream}; use futures::future::{err, Either};
use futures::{Future, Stream};
mod db;
mod models; mod models;
mod schema; mod schema;
use db::{CreateUser, DbExecutor}; type Pool = r2d2::Pool<ConnectionManager<SqliteConnection>>;
/// State with DbExecutor address /// Diesel query
struct AppState { fn query(
db: Addr<DbExecutor>, nm: String,
pool: web::State<Pool>,
) -> Result<models::User, diesel::result::Error> {
use self::schema::users::dsl::*;
let uuid = format!("{}", uuid::Uuid::new_v4());
let new_user = models::NewUser {
id: &uuid,
name: nm.as_str(),
};
let conn: &SqliteConnection = &pool.get().unwrap();
diesel::insert_into(users).values(&new_user).execute(conn)?;
let mut items = users.filter(id.eq(&uuid)).load::<models::User>(conn)?;
Ok(items.pop().unwrap())
} }
/// Async request handler /// Async request handler
fn add( fn add(
(name, state): (Path<String>, State<AppState>), name: web::Path<String>,
) -> FutureResponse<HttpResponse> { pool: web::State<Pool>,
// send async `CreateUser` message to a `DbExecutor` ) -> impl Future<Item = HttpResponse, Error = Error> {
state // run diesel blocking code
.db web::block(move || query(name.into_inner(), pool)).then(|res| match res {
.send(CreateUser {
name: name.into_inner(),
})
.from_err()
.and_then(|res| match res {
Ok(user) => Ok(HttpResponse::Ok().json(user)), Ok(user) => Ok(HttpResponse::Ok().json(user)),
Err(_) => Ok(HttpResponse::InternalServerError().into()), Err(_) => Ok(HttpResponse::InternalServerError().into()),
}) })
.responder()
} }
#[derive(Debug, Serialize, Deserialize)] #[derive(Debug, Serialize, Deserialize)]
struct MyUser { struct MyUser {
name: String name: String,
} }
const MAX_SIZE: usize = 262_144; // max payload size is 256k const MAX_SIZE: usize = 262_144; // max payload size is 256k
/// This handler manually load request payload and parse json object /// This handler manually load request payload and parse json object
fn index_add((req, state): (HttpRequest<AppState>, State<AppState>)) -> impl Future<Item = HttpResponse, Error = Error> { fn index_add<P>(
// HttpRequest::payload() is stream of Bytes objects pl: web::Payload<P>,
req.payload() pool: web::State<Pool>,
) -> impl Future<Item = HttpResponse, Error = Error>
where
P: Stream<Item = Bytes, Error = error::PayloadError>,
{
pl
// `Future::from_err` acts like `?` in that it coerces the error type from // `Future::from_err` acts like `?` in that it coerces the error type from
// the future into the final error type // the future into the final error type
.from_err() .from_err()
// `fold` will asynchronously read each chunk of the request body and // `fold` will asynchronously read each chunk of the request body and
// call supplied closure, then it resolves to result of closure // call supplied closure, then it resolves to result of closure
.fold(BytesMut::new(), move |mut body, chunk| { .fold(BytesMut::new(), move |mut body, chunk| {
@ -92,45 +89,39 @@ fn index_add((req, state): (HttpRequest<AppState>, State<AppState>)) -> impl Fut
// Douman NOTE: // Douman NOTE:
// The return value in this closure helps, to clarify result for compiler // The return value in this closure helps, to clarify result for compiler
// as otheriwse it cannot understand it // as otheriwse it cannot understand it
.and_then(move |body| -> Box<Future<Item = HttpResponse, Error = Error>> { .and_then(move |body| {
// body is loaded, now we can deserialize serde-json // body is loaded, now we can deserialize serde-json
let r_obj = serde_json::from_slice::<MyUser>(&body); let r_obj = serde_json::from_slice::<MyUser>(&body);
// Send to the db for create // Send to the db for create
match r_obj { match r_obj {
Ok(obj) => { Ok(obj) => {
let res = state.db.send(CreateUser { name: obj.name, }) Either::A(web::block(move || query(obj.name, pool)).then(|res| {
.from_err() match res {
.and_then(|res| match res {
Ok(user) => Ok(HttpResponse::Ok().json(user)), Ok(user) => Ok(HttpResponse::Ok().json(user)),
Err(_) => Ok(HttpResponse::InternalServerError().into()), Err(_) => Ok(HttpResponse::InternalServerError().into()),
});
Box::new(res)
} }
Err(_) => Box::new(future::err(error::ErrorBadRequest("Json Decode Failed"))) }))
}
Err(_) => Either::B(err(error::ErrorBadRequest("Json Decode Failed"))),
} }
}) })
} }
fn add2((item, state): (Json<MyUser>, State<AppState>)) -> impl Future<Item = HttpResponse, Error = Error> { fn add2(
state.db item: web::Json<MyUser>,
.send(CreateUser { pool: web::State<Pool>,
// into_inner to move into the reference, then accessing name to ) -> impl Future<Item = HttpResponse, Error = Error> {
// move the name out. // run diesel blocking code
name: item.into_inner().name, web::block(move || query(item.into_inner().name, pool)).then(|res| match res {
})
.from_err()
.and_then(|res| match res {
Ok(user) => Ok(HttpResponse::Ok().json(user)), Ok(user) => Ok(HttpResponse::Ok().json(user)),
Err(_) => Ok(HttpResponse::InternalServerError().into()), Err(_) => Ok(HttpResponse::InternalServerError().into()),
}) })
} }
fn main() { fn main() -> std::io::Result<()> {
::std::env::set_var("RUST_LOG", "actix_web=info"); std::env::set_var("RUST_LOG", "actix_web=info");
env_logger::init(); env_logger::init();
let sys = actix::System::new("diesel-example");
// Start 3 db executor actors // Start 3 db executor actors
let manager = ConnectionManager::<SqliteConnection>::new("test.db"); let manager = ConnectionManager::<SqliteConnection>::new("test.db");
@ -138,32 +129,29 @@ fn main() {
.build(manager) .build(manager)
.expect("Failed to create pool."); .expect("Failed to create pool.");
let addr = SyncArbiter::start(3, move || DbExecutor(pool.clone()));
// Start http server // Start http server
server::new(move || { HttpServer::new(move || {
App::with_state(AppState{db: addr.clone()}) App::new()
.state(pool.clone())
// enable logger // enable logger
.middleware(middleware::Logger::default()) .middleware(middleware::Logger::default())
// This can be called with: // This can be called with:
// curl -S --header "Content-Type: application/json" --request POST --data '{"name":"xyz"}' http://127.0.0.1:8080/add // curl -S --header "Content-Type: application/json" --request POST --data '{"name":"xyz"}' http://127.0.0.1:8080/add
// Use of the extractors makes some post conditions simpler such // Use of the extractors makes some post conditions simpler such
// as size limit protections and built in json validation. // as size limit protections and built in json validation.
.resource("/add2", |r| { .service(
r.method(http::Method::POST) web::resource("/add2").route(
.with_async_config(add2, |(json_cfg, )| { web::post()
json_cfg.0.limit(4096); // <- limit size of the payload .config(web::JsonConfig::default().limit(4096)) // <- limit size of the payload
}) .to_async(add2),
}) ),
)
// Manual parsing would allow custom error construction, use of // Manual parsing would allow custom error construction, use of
// other parsers *beside* json (for example CBOR, protobuf, xml), and allows // other parsers *beside* json (for example CBOR, protobuf, xml), and allows
// an application to standardise on a single parser implementation. // an application to standardise on a single parser implementation.
.resource("/add", |r| r.method(http::Method::POST).with_async(index_add)) .service(web::resource("/add").route(web::post().to_async(index_add)))
.resource("/add/{name}", |r| r.method(http::Method::GET).with(add)) .service(web::resource("/add/{name}").route(web::get().to_async(add)))
}).bind("127.0.0.1:8080") })
.unwrap() .bind("127.0.0.1:8080")?
.start(); .run()
println!("Started http server: 127.0.0.1:8080");
let _ = sys.run();
} }

View File

@ -2,9 +2,12 @@
name = "json-example" name = "json-example"
version = "0.1.0" version = "0.1.0"
authors = ["Nikolay Kim <fafhrd91@gmail.com>"] authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
workspace = "../" workspace = ".."
edition = "2018"
[dependencies] [dependencies]
actix-web = { git="https://github.com/actix/actix-web.git", branch = "1.0" }
bytes = "0.4" bytes = "0.4"
futures = "0.1" futures = "0.1"
env_logger = "*" env_logger = "*"
@ -13,6 +16,3 @@ serde = "1.0"
serde_json = "1.0" serde_json = "1.0"
serde_derive = "1.0" serde_derive = "1.0"
json = "*" json = "*"
actix = "0.7"
actix-web = "^0.7"

View File

@ -1,22 +1,13 @@
extern crate actix;
extern crate actix_web;
extern crate bytes;
extern crate env_logger;
extern crate futures;
extern crate serde_json;
#[macro_use]
extern crate serde_derive;
#[macro_use] #[macro_use]
extern crate json; extern crate json;
use actix_web::{ use actix_web::{
error, http, middleware, server, App, AsyncResponder, Error, HttpMessage, error, middleware, web, App, Error, HttpRequest, HttpResponse, HttpServer,
HttpRequest, HttpResponse, Json,
}; };
use bytes::{Bytes, BytesMut};
use bytes::BytesMut;
use futures::{Future, Stream}; use futures::{Future, Stream};
use json::JsonValue; use json::JsonValue;
use serde_derive::{Deserialize, Serialize};
#[derive(Debug, Serialize, Deserialize)] #[derive(Debug, Serialize, Deserialize)]
struct MyObj { struct MyObj {
@ -24,39 +15,34 @@ struct MyObj {
number: i32, number: i32,
} }
/// This handler uses `HttpRequest::json()` for loading json object.
fn index(req: &HttpRequest) -> Box<Future<Item = HttpResponse, Error = Error>> {
req.json()
.from_err() // convert all errors into `Error`
.and_then(|val: MyObj| {
println!("model: {:?}", val);
Ok(HttpResponse::Ok().json(val)) // <- send response
})
.responder()
}
/// This handler uses json extractor /// This handler uses json extractor
fn extract_item(item: Json<MyObj>) -> HttpResponse { fn index(item: web::Json<MyObj>) -> HttpResponse {
println!("model: {:?}", &item); println!("model: {:?}", &item);
HttpResponse::Ok().json(item.0) // <- send response HttpResponse::Ok().json(item.0) // <- send response
} }
/// This handler uses json extractor with limit /// This handler uses json extractor with limit
fn extract_item_limit((item, _req): (Json<MyObj>, HttpRequest)) -> HttpResponse { fn extract_item(item: web::Json<MyObj>, req: HttpRequest) -> HttpResponse {
println!("model: {:?}", &item); println!("request: {:?}", req);
HttpResponse::Ok().json(item.0) // <- send response println!("model: {:?}", item);
HttpResponse::Ok().json(item.0) // <- send json response
} }
const MAX_SIZE: usize = 262_144; // max payload size is 256k const MAX_SIZE: usize = 262_144; // max payload size is 256k
/// This handler manually load request payload and parse json object /// This handler manually load request payload and parse json object
fn index_manual(req: &HttpRequest) -> Box<Future<Item = HttpResponse, Error = Error>> { fn index_manual<P>(
// HttpRequest::payload() is stream of Bytes objects payload: web::Payload<P>,
req.payload() ) -> impl Future<Item = HttpResponse, Error = Error>
where
P: Stream<Item = Bytes, Error = error::PayloadError>,
{
// payload is a stream of Bytes objects
payload
// `Future::from_err` acts like `?` in that it coerces the error type from // `Future::from_err` acts like `?` in that it coerces the error type from
// the future into the final error type // the future into the final error type
.from_err() .from_err()
// `fold` will asynchronously read each chunk of the request body and // `fold` will asynchronously read each chunk of the request body and
// call supplied closure, then it resolves to result of closure // call supplied closure, then it resolves to result of closure
.fold(BytesMut::new(), move |mut body, chunk| { .fold(BytesMut::new(), move |mut body, chunk| {
@ -75,59 +61,56 @@ fn index_manual(req: &HttpRequest) -> Box<Future<Item = HttpResponse, Error = Er
let obj = serde_json::from_slice::<MyObj>(&body)?; let obj = serde_json::from_slice::<MyObj>(&body)?;
Ok(HttpResponse::Ok().json(obj)) // <- send response Ok(HttpResponse::Ok().json(obj)) // <- send response
}) })
.responder()
} }
/// This handler manually load request payload and parse json-rust /// This handler manually load request payload and parse json-rust
fn index_mjsonrust( fn index_mjsonrust<P>(
req: &HttpRequest, pl: web::Payload<P>,
) -> Box<Future<Item = HttpResponse, Error = Error>> { ) -> impl Future<Item = HttpResponse, Error = Error>
req.payload() where
.concat2() P: Stream<Item = Bytes, Error = error::PayloadError>,
.from_err() {
.and_then(|body| { pl.concat2().from_err().and_then(|body| {
// body is loaded, now we can deserialize json-rust // body is loaded, now we can deserialize json-rust
let result = json::parse(std::str::from_utf8(&body).unwrap()); // return Result let result = json::parse(std::str::from_utf8(&body).unwrap()); // return Result
let injson: JsonValue = match result { let injson: JsonValue = match result {
Ok(v) => v, Ok(v) => v,
Err(e) => object!{"err" => e.to_string() }, Err(e) => json::object! {"err" => e.to_string() },
}; };
Ok(HttpResponse::Ok() Ok(HttpResponse::Ok()
.content_type("application/json") .content_type("application/json")
.body(injson.dump())) .body(injson.dump()))
}) })
.responder()
} }
fn main() { fn main() -> std::io::Result<()> {
::std::env::set_var("RUST_LOG", "actix_web=info"); std::env::set_var("RUST_LOG", "actix_web=info");
env_logger::init(); env_logger::init();
let sys = actix::System::new("json-example");
server::new(|| { HttpServer::new(|| {
App::new() App::new()
// enable logger // enable logger
.middleware(middleware::Logger::default()) .middleware(middleware::Logger::default())
.resource("/extractor", |r| { .service(
r.method(http::Method::POST) web::resource("/extractor").route(
.with_config(extract_item, |(cfg,)| { web::post()
cfg.limit(4096); // <- limit size of the payload .config(web::JsonConfig::default().limit(4096)) // <- limit size of the payload
.to(index),
),
)
.service(
web::resource("/extractor2").route(
web::post()
.config(web::JsonConfig::default().limit(4096)) // <- limit size of the payload
.to_async(extract_item),
),
)
.service(web::resource("/manual").route(web::post().to_async(index_manual)))
.service(
web::resource("/mjsonrust").route(web::post().to_async(index_mjsonrust)),
)
.service(web::resource("/").route(web::post().to(index)))
}) })
}) .bind("127.0.0.1:8080")?
.resource("/extractor2", |r| { .run()
r.method(http::Method::POST)
.with_config(extract_item_limit, |((cfg, _),)| {
cfg.limit(4096); // <- limit size of the payload
})
})
.resource("/manual", |r| r.method(http::Method::POST).f(index_manual))
.resource("/mjsonrust", |r| r.method(http::Method::POST).f(index_mjsonrust))
.resource("/", |r| r.method(http::Method::POST).f(index))
}).bind("127.0.0.1:8080")
.unwrap()
.shutdown_timeout(1)
.start();
println!("Started http server: 127.0.0.1:8080");
let _ = sys.run();
} }

View File

@ -1,10 +1,7 @@
//! Actix web r2d2 example //! Actix web r2d2 example
use std::io; use std::io;
use actix_web::{ use actix_web::{middleware, web, App, Error, HttpResponse, HttpServer};
blocking, extract::Path, middleware, web, App, Error, HttpResponse, HttpServer,
State,
};
use futures::Future; use futures::Future;
use r2d2::Pool; use r2d2::Pool;
use r2d2_sqlite::SqliteConnectionManager; use r2d2_sqlite::SqliteConnectionManager;
@ -12,11 +9,11 @@ use uuid;
/// Async request handler. Ddb pool is stored in application state. /// Async request handler. Ddb pool is stored in application state.
fn index( fn index(
path: Path<String>, path: web::Path<String>,
db: State<Pool<SqliteConnectionManager>>, db: web::State<Pool<SqliteConnectionManager>>,
) -> impl Future<Item = HttpResponse, Error = Error> { ) -> impl Future<Item = HttpResponse, Error = Error> {
// execute sync code in threadpool // execute sync code in threadpool
blocking::run(move || { web::block(move || {
let conn = db.get().unwrap(); let conn = db.get().unwrap();
let uuid = format!("{}", uuid::Uuid::new_v4()); let uuid = format!("{}", uuid::Uuid::new_v4());

View File

@ -2,11 +2,11 @@
name = "state" name = "state"
version = "0.1.0" version = "0.1.0"
authors = ["Nikolay Kim <fafhrd91@gmail.com>"] authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
workspace = "../" workspace = ".."
edition = "2018"
[dependencies] [dependencies]
futures = "0.1" actix-web = { git="https://github.com/actix/actix-web.git", branch = "1.0" }
env_logger = "0.5"
actix = "0.7" futures = "0.1"
actix-web = "0.7" env_logger = "0.6"

View File

@ -1,7 +1,7 @@
#![cfg_attr(feature = "cargo-clippy", allow(needless_pass_by_value))] #![cfg_attr(feature = "cargo-clippy", allow(needless_pass_by_value))]
//! There are two level of statefulness in actix-web. Application has state //! Application may have multiple states that are shared across
//! that is shared across all handlers within same Application. //! all handlers within same Application. State could be added
//! And individual handler can have state. //! with `App::state()` method, multiple different states could be added.
//! //!
//! > **Note**: http server accepts an application factory rather than an //! > **Note**: http server accepts an application factory rather than an
//! application > instance. Http server constructs an application instance for //! application > instance. Http server constructs an application instance for
@ -11,45 +11,34 @@
//! //!
//! Check [user guide](https://actix.rs/book/actix-web/sec-2-application.html) for more info. //! Check [user guide](https://actix.rs/book/actix-web/sec-2-application.html) for more info.
extern crate actix; use std::io;
extern crate actix_web; use std::sync::{Arc, Mutex};
extern crate env_logger;
use std::sync::Arc; use actix_web::{middleware, web, App, HttpRequest, HttpResponse, HttpServer};
use std::sync::Mutex;
use actix_web::{middleware, server, App, HttpRequest, HttpResponse};
/// Application state
struct AppState {
counter: Arc<Mutex<usize>>,
}
/// simple handle /// simple handle
fn index(req: &HttpRequest<AppState>) -> HttpResponse { fn index(state: web::State<Arc<Mutex<usize>>>, req: HttpRequest) -> HttpResponse {
println!("{:?}", req); println!("{:?}", req);
*(req.state().counter.lock().unwrap()) += 1; *(state.lock().unwrap()) += 1;
HttpResponse::Ok().body(format!("Num of requests: {}", req.state().counter.lock().unwrap())) HttpResponse::Ok().body(format!("Num of requests: {}", state.lock().unwrap()))
} }
fn main() { fn main() -> io::Result<()> {
::std::env::set_var("RUST_LOG", "actix_web=info"); std::env::set_var("RUST_LOG", "actix_web=info");
env_logger::init(); env_logger::init();
let sys = actix::System::new("ws-example");
let counter = Arc::new(Mutex::new(0)); let counter = Arc::new(Mutex::new(0));
//move is necessary to give closure below ownership of counter //move is necessary to give closure below ownership of counter
server::new(move || { HttpServer::new(move || {
App::with_state(AppState{counter: counter.clone()}) // <- create app with shared state App::new()
.state(counter.clone()) // <- create app with shared state
// enable logger // enable logger
.middleware(middleware::Logger::default()) .middleware(middleware::Logger::default())
// register simple handler, handle all methods // register simple handler, handle all methods
.resource("/", |r| r.f(index)) .service(web::resource("/").to(index))
}).bind("127.0.0.1:8080") })
.unwrap() .bind("127.0.0.1:8080")?
.start(); .run()
println!("Started http server: 127.0.0.1:8080");
let _ = sys.run();
} }