From 09b0188ff99e872898793bd815382a4105219b77 Mon Sep 17 00:00:00 2001 From: Nikolay Kim Date: Sun, 14 Apr 2019 10:34:41 -0700 Subject: [PATCH] upgrade to alpha.6 --- async_ex1/src/main.rs | 12 ++---- async_ex2/src/appconfig.rs | 31 +++++---------- async_ex2/src/bin/main.rs | 11 ++---- async_ex2/src/common.rs | 4 +- async_ex2/src/handlers/mod.rs | 3 +- async_ex2/src/handlers/parts.rs | 32 +++++++++------- async_ex2/src/handlers/products.rs | 53 ++++++++++++++------------ basics/src/main.rs | 9 +++-- http-full-proxy/src/main.rs | 2 +- middleware/src/redirect.rs | 14 +++---- middleware/src/simple.rs | 15 ++++---- multipart/src/main.rs | 19 ++------- simple-auth-server/src/auth_handler.rs | 5 ++- 13 files changed, 93 insertions(+), 117 deletions(-) diff --git a/async_ex1/src/main.rs b/async_ex1/src/main.rs index 7057e694..1bb4fd2d 100644 --- a/async_ex1/src/main.rs +++ b/async_ex1/src/main.rs @@ -12,7 +12,6 @@ // - POSTing json body // 3. chaining futures into a single response used by an asynch endpoint - #[macro_use] extern crate validator_derive; #[macro_use] @@ -47,8 +46,6 @@ struct HttpBinResponse { url: String, } - - /// post json to httpbin, get it back in the response body, return deserialized fn step_x( data: SomeData, @@ -93,12 +90,9 @@ fn main() -> io::Result<()> { println!("Starting server at: {:?}", endpoint); HttpServer::new(|| { - App::new() - .data(Client::default()) - .service( - web::resource("/something") - .route(web::post().to_async(create_something)), - ) + App::new().data(Client::default()).service( + web::resource("/something").route(web::post().to_async(create_something)), + ) }) .bind(endpoint)? .run() diff --git a/async_ex2/src/appconfig.rs b/async_ex2/src/appconfig.rs index ae23b09c..e38629a6 100644 --- a/async_ex2/src/appconfig.rs +++ b/async_ex2/src/appconfig.rs @@ -1,47 +1,36 @@ use actix_web::{error, web}; -use bytes::Bytes; -use futures::Stream; -use crate::{ - handlers::{ - products, - parts - }, -}; +use crate::handlers::{parts, products}; - -pub fn config_app

(cfg: &mut web::RouterConfig

) - where P: Stream - + 'static -{ +pub fn config_app(cfg: &mut web::RouterConfig) { // domain includes: /products/{product_id}/parts/{part_id} cfg.service( web::scope("/products") .service( web::resource("") .route(web::get().to_async(products::get_products)) - .route(web::post().to_async(products::add_product)) + .route(web::post().to_async(products::add_product)), ) .service( web::scope("/{product_id}") .service( web::resource("") .route(web::get().to_async(products::get_product_detail)) - .route(web::delete().to_async(products::remove_product)) + .route(web::delete().to_async(products::remove_product)), ) .service( web::scope("/parts") .service( web::resource("") .route(web::get().to_async(parts::get_parts)) - .route(web::post().to_async(parts::add_part)) + .route(web::post().to_async(parts::add_part)), ) .service( web::resource("/{part_id}") .route(web::get().to_async(parts::get_part_detail)) - .route(web::delete().to_async(parts::remove_part)) - ) - ) - ) + .route(web::delete().to_async(parts::remove_part)), + ), + ), + ), ); -} \ No newline at end of file +} diff --git a/async_ex2/src/bin/main.rs b/async_ex2/src/bin/main.rs index 44c9c7e7..f5ee4fb9 100644 --- a/async_ex2/src/bin/main.rs +++ b/async_ex2/src/bin/main.rs @@ -1,19 +1,16 @@ use actix_web::{middleware, App, HttpServer}; -use async_ex2::{ - appconfig::config_app, -}; - +use async_ex2::appconfig::config_app; fn main() -> std::io::Result<()> { std::env::set_var("RUST_LOG", "actix_server=info,actix_web=info"); env_logger::init(); - HttpServer::new(|| + HttpServer::new(|| { App::new() .configure(config_app) .wrap(middleware::Logger::default()) - ) + }) .bind("127.0.0.1:8080")? .run() -} \ No newline at end of file +} diff --git a/async_ex2/src/common.rs b/async_ex2/src/common.rs index 4359c2ec..4c100617 100644 --- a/async_ex2/src/common.rs +++ b/async_ex2/src/common.rs @@ -1,6 +1,5 @@ use serde::{Deserialize, Serialize}; - #[derive(Deserialize, Serialize)] pub struct Product { id: Option, @@ -8,10 +7,9 @@ pub struct Product { name: Option, } - #[derive(Deserialize, Serialize)] pub struct Part { id: Option, part_type: Option, name: Option, -} \ No newline at end of file +} diff --git a/async_ex2/src/handlers/mod.rs b/async_ex2/src/handlers/mod.rs index 17f9e2c2..299c561b 100644 --- a/async_ex2/src/handlers/mod.rs +++ b/async_ex2/src/handlers/mod.rs @@ -1,3 +1,2 @@ -pub mod products; pub mod parts; - +pub mod products; diff --git a/async_ex2/src/handlers/parts.rs b/async_ex2/src/handlers/parts.rs index 22bb017a..0dba7b0f 100644 --- a/async_ex2/src/handlers/parts.rs +++ b/async_ex2/src/handlers/parts.rs @@ -1,26 +1,32 @@ -use actix_multipart::{Field, Item, Multipart, MultipartError}; -use actix_web::{HttpResponse, web, error, Error}; -use futures::{future::{ok as fut_ok, err as fut_err, Either}, Future, Stream}; +use actix_multipart::{Field, Multipart, MultipartError}; +use actix_web::{error, web, Error, HttpResponse}; +use futures::{ + future::{err as fut_err, ok as fut_ok, Either}, + Future, Stream, +}; use crate::common::{Part, Product}; - -pub fn get_parts(query: web::Query>) - -> impl Future { +pub fn get_parts( + query: web::Query>, +) -> impl Future { fut_ok(HttpResponse::Ok().finish()) } -pub fn add_part(new_part: web::Json) - -> impl Future { +pub fn add_part( + new_part: web::Json, +) -> impl Future { fut_ok(HttpResponse::Ok().finish()) } -pub fn get_part_detail(id: web::Path) - -> impl Future { +pub fn get_part_detail( + id: web::Path, +) -> impl Future { fut_ok(HttpResponse::Ok().finish()) } -pub fn remove_part(id: web::Path) - -> impl Future { +pub fn remove_part( + id: web::Path, +) -> impl Future { fut_ok(HttpResponse::Ok().finish()) -} \ No newline at end of file +} diff --git a/async_ex2/src/handlers/products.rs b/async_ex2/src/handlers/products.rs index 174b8286..1f3d68fd 100644 --- a/async_ex2/src/handlers/products.rs +++ b/async_ex2/src/handlers/products.rs @@ -1,54 +1,57 @@ -use actix_multipart::{Field, Item, Multipart, MultipartError}; -use actix_web::{HttpResponse, web, error, Error}; -use futures::{future::{ok as fut_ok, err as fut_err, Either}, Future, Stream}; +use actix_multipart::{Field, Multipart, MultipartError}; +use actix_web::{error, web, Error, HttpResponse}; +use futures::{ + future::{err as fut_err, ok as fut_ok, Either}, + Future, Stream, +}; use crate::common::{Part, Product}; - -pub fn get_products(query: web::Query>) - -> impl Future { +pub fn get_products( + query: web::Query>, +) -> impl Future { fut_ok(HttpResponse::Ok().finish()) } -pub fn add_product(new_product: web::Json) - -> impl Future { +pub fn add_product( + new_product: web::Json, +) -> impl Future { fut_ok(HttpResponse::Ok().finish()) } -pub fn get_product_detail(id: web::Path) - -> impl Future { +pub fn get_product_detail( + id: web::Path, +) -> impl Future { fut_ok(HttpResponse::Ok().finish()) } -pub fn remove_product(id: web::Path) - -> impl Future { +pub fn remove_product( + id: web::Path, +) -> impl Future { fut_ok(HttpResponse::Ok().finish()) } - #[cfg(test)] mod tests { use super::*; - use actix_service::Service; - use actix_web::{test, HttpResponse, HttpRequest, App, - http::{header, StatusCode}, web}; use crate::appconfig::config_app; - + use actix_service::Service; + use actix_web::{ + http::{header, StatusCode}, + test, web, App, HttpRequest, HttpResponse, + }; #[test] fn test_add_product() { - let mut app = test::init_service( - App::new() - .configure(config_app) - ); + let mut app = test::init_service(App::new().configure(config_app)); let payload = r#"{"id":12345,"product_type":"fancy","name":"test"}"#.as_bytes(); let req = test::TestRequest::post() - .uri("/products") - .header(header::CONTENT_TYPE, "application/json") - .set_payload(payload) - .to_request(); + .uri("/products") + .header(header::CONTENT_TYPE, "application/json") + .set_payload(payload) + .to_request(); let resp = test::block_on(app.call(req)).unwrap(); diff --git a/basics/src/main.rs b/basics/src/main.rs index 7ab8a725..5d74e3d9 100644 --- a/basics/src/main.rs +++ b/basics/src/main.rs @@ -124,16 +124,17 @@ fn main() -> io::Result<()> { .finish() }))) // default - .default_resource(|r| { + .default_service( // 404 for GET request - r.route(web::get().to(p404)) + web::resource("") + .route(web::get().to(p404)) // all requests that are not `GET` .route( web::route() .guard(guard::Not(guard::Get())) .to(|| HttpResponse::MethodNotAllowed()), - ) - }) + ), + ) }) .bind("127.0.0.1:8080")? .start(); diff --git a/http-full-proxy/src/main.rs b/http-full-proxy/src/main.rs index 93eacbc8..2d7a8426 100644 --- a/http-full-proxy/src/main.rs +++ b/http-full-proxy/src/main.rs @@ -98,7 +98,7 @@ fn main() -> std::io::Result<()> { App::new() .data(forward_url.clone()) .wrap(middleware::Logger::default()) - .default_resource(|r| r.to_async(forward)) + .default_service(web::route().to_async(forward)) }) .bind((listen_addr, listen_port))? .system_exit() diff --git a/middleware/src/redirect.rs b/middleware/src/redirect.rs index 3ffd3a87..670caa4a 100644 --- a/middleware/src/redirect.rs +++ b/middleware/src/redirect.rs @@ -6,12 +6,12 @@ use futures::Poll; pub struct CheckLogin; -impl Transform for CheckLogin +impl Transform for CheckLogin where - S: Service, Response = ServiceResponse>, + S: Service>, S::Future: 'static, { - type Request = ServiceRequest

; + type Request = ServiceRequest; type Response = ServiceResponse; type Error = S::Error; type InitError = (); @@ -26,12 +26,12 @@ pub struct CheckLoginMiddleware { service: S, } -impl Service for CheckLoginMiddleware +impl Service for CheckLoginMiddleware where - S: Service, Response = ServiceResponse>, + S: Service>, S::Future: 'static, { - type Request = ServiceRequest

; + type Request = ServiceRequest; type Response = ServiceResponse; type Error = S::Error; type Future = Either>; @@ -40,7 +40,7 @@ where self.service.poll_ready() } - fn call(&mut self, req: ServiceRequest

) -> Self::Future { + fn call(&mut self, req: ServiceRequest) -> Self::Future { // We only need to hook into the `start` for this middleware. let is_logged_in = false; // Change this to see the change in outcome in the browser diff --git a/middleware/src/simple.rs b/middleware/src/simple.rs index 68f6e143..277257e4 100644 --- a/middleware/src/simple.rs +++ b/middleware/src/simple.rs @@ -11,16 +11,15 @@ pub struct SayHi; // Middleware factory is `Transform` trait from actix-service crate // `S` - type of the next service -// `P` - type of request's payload // `B` - type of response's body -impl Transform for SayHi +impl Transform for SayHi where - S: Service, Response = ServiceResponse>, + S: Service>, S::Future: 'static, S::Error: 'static, B: 'static, { - type Request = ServiceRequest

; + type Request = ServiceRequest; type Response = ServiceResponse; type Error = S::Error; type InitError = (); @@ -36,14 +35,14 @@ pub struct SayHiMiddleware { service: S, } -impl Service for SayHiMiddleware +impl Service for SayHiMiddleware where - S: Service, Response = ServiceResponse>, + S: Service>, S::Future: 'static, S::Error: 'static, B: 'static, { - type Request = ServiceRequest

; + type Request = ServiceRequest; type Response = ServiceResponse; type Error = S::Error; type Future = Box>; @@ -52,7 +51,7 @@ where self.service.poll_ready() } - fn call(&mut self, req: ServiceRequest

) -> Self::Future { + fn call(&mut self, req: ServiceRequest) -> Self::Future { println!("Hi from start. You requested: {}", req.path()); Box::new(self.service.call(req).and_then(|res| { diff --git a/multipart/src/main.rs b/multipart/src/main.rs index 7c859b14..5505af8e 100644 --- a/multipart/src/main.rs +++ b/multipart/src/main.rs @@ -1,8 +1,8 @@ use std::cell::Cell; -use std::fs::{self}; +use std::fs; use std::io::Write; -use actix_multipart::{Field, Item, Multipart, MultipartError}; +use actix_multipart::{Field, Multipart, MultipartError}; use actix_web::{error, middleware, web, App, Error, HttpResponse, HttpServer}; use futures::future::{err, Either}; use futures::{Future, Stream}; @@ -15,7 +15,7 @@ pub fn save_file(field: Field) -> impl Future { let file_path_string = "upload.png"; let mut file = match fs::File::create(file_path_string) { Ok(file) => file, - Err(e) => return Either::A(err(error::ErrorInternalServerError(e))) + Err(e) => return Either::A(err(error::ErrorInternalServerError(e))), }; Either::B( field @@ -34,17 +34,6 @@ pub fn save_file(field: Field) -> impl Future { ) } -pub fn handle_multipart_item(item: Item) -> Box> { - match item { - Item::Field(field) => Box::new(save_file(field).into_stream()), - Item::Nested(mp) => Box::new( - mp.map_err(error::ErrorInternalServerError) - .map(handle_multipart_item) - .flatten(), - ), - } -} - pub fn upload( multipart: Multipart, counter: web::Data>, @@ -54,7 +43,7 @@ pub fn upload( multipart .map_err(error::ErrorInternalServerError) - .map(handle_multipart_item) + .map(|field| save_file(field).into_stream()) .flatten() .collect() .map(|sizes| HttpResponse::Ok().json(sizes)) diff --git a/simple-auth-server/src/auth_handler.rs b/simple-auth-server/src/auth_handler.rs index 0a433e5a..444063a6 100644 --- a/simple-auth-server/src/auth_handler.rs +++ b/simple-auth-server/src/auth_handler.rs @@ -46,11 +46,12 @@ impl Handler for DbExecutor { // simple aliasing makes the intentions clear and its more readable pub type LoggedUser = SlimUser; -impl

FromRequest

for LoggedUser { +impl FromRequest for LoggedUser { + type Config = (); type Error = Error; type Future = Result; - fn from_request(req: &HttpRequest, pl: &mut Payload

) -> Self::Future { + fn from_request(req: &HttpRequest, pl: &mut Payload) -> Self::Future { if let Some(identity) = Identity::from_request(req, pl)?.identity() { let user: SlimUser = decode_token(&identity)?; return Ok(user as LoggedUser);