From 20517d415d80172b70f593e494d3d5ff90479034 Mon Sep 17 00:00:00 2001 From: Dominic Date: Sat, 28 Dec 2019 16:26:17 +0100 Subject: [PATCH] Update examples/{extractors, errors} to futures 0.3 and actix-web 2.0 (#130) * Update to futures 0.3 * update examples/errors to actix-web 2.0 --- examples/errors/Cargo.toml | 10 +++++---- examples/errors/src/helpers.rs | 10 ++++----- examples/errors/src/logging.rs | 10 ++++----- examples/errors/src/main.rs | 12 +++++------ examples/errors/src/override_error.rs | 31 ++++++++++++++++----------- examples/errors/src/recommend_one.rs | 22 +++++++++++-------- examples/errors/src/recommend_two.rs | 22 +++++++++++-------- examples/extractors/Cargo.toml | 5 +++-- examples/extractors/src/form.rs | 10 ++++----- examples/extractors/src/json_one.rs | 10 ++++----- examples/extractors/src/json_two.rs | 10 ++++----- examples/extractors/src/main.rs | 20 +++++++++-------- examples/extractors/src/multiple.rs | 10 ++++----- examples/extractors/src/path_one.rs | 10 ++++----- examples/extractors/src/path_three.rs | 10 ++++----- examples/extractors/src/path_two.rs | 10 ++++----- examples/extractors/src/query.rs | 10 ++++----- 17 files changed, 120 insertions(+), 102 deletions(-) diff --git a/examples/errors/Cargo.toml b/examples/errors/Cargo.toml index 0b605e2..ed0f4f6 100644 --- a/examples/errors/Cargo.toml +++ b/examples/errors/Cargo.toml @@ -4,7 +4,9 @@ version = "1.0.0" edition = "2018" [dependencies] -actix-web = "1.0" -failure = "0.1" -env_logger = "0.6" -log = "0.4" +actix-web = "2.0.0" +actix-rt = "1.0.0" +env_logger = "0.7.1" +log = "0.4.8" +failure = "0.1.6" +actix-http = "1.0.1" diff --git a/examples/errors/src/helpers.rs b/examples/errors/src/helpers.rs index 6dc01fd..690a2d2 100644 --- a/examples/errors/src/helpers.rs +++ b/examples/errors/src/helpers.rs @@ -7,19 +7,19 @@ struct MyError { name: &'static str, } -pub fn index() -> Result<&'static str> { +async fn index() -> Result<&'static str> { let result: Result<&'static str, MyError> = Err(MyError { name: "test error" }); Ok(result.map_err(|e| error::ErrorBadRequest(e.name))?) } // -pub fn main() { +#[actix_rt::main] +async fn main() -> std::io::Result<()> { use actix_web::HttpServer; HttpServer::new(|| App::new().route("/", web::get().to(index))) - .bind("127.0.0.1:8088") - .unwrap() + .bind("127.0.0.1:8088")? .run() - .unwrap(); + .await } diff --git a/examples/errors/src/logging.rs b/examples/errors/src/logging.rs index 9f5b880..5e4987d 100644 --- a/examples/errors/src/logging.rs +++ b/examples/errors/src/logging.rs @@ -12,13 +12,14 @@ pub struct MyError { // Use default implementation for `error_response()` method impl error::ResponseError for MyError {} -pub fn index() -> Result<&'static str, MyError> { +async fn index() -> Result<&'static str, MyError> { let err = MyError { name: "test error" }; debug!("{}", err); Err(err) } -pub fn main() { +#[actix_rt::main] +async fn main() -> std::io::Result<()> { use actix_web::{middleware::Logger, web, App, HttpServer}; std::env::set_var("RUST_LOG", "my_errors=debug,actix_web=info"); @@ -30,9 +31,8 @@ pub fn main() { .wrap(Logger::default()) .route("/", web::get().to(index)) }) - .bind("127.0.0.1:8088") - .unwrap() + .bind("127.0.0.1:8088")? .run() - .unwrap(); + .await } // diff --git a/examples/errors/src/main.rs b/examples/errors/src/main.rs index c9e4984..ac6d13b 100644 --- a/examples/errors/src/main.rs +++ b/examples/errors/src/main.rs @@ -10,24 +10,24 @@ use failure::Fail; #[derive(Fail, Debug)] #[fail(display = "my error")] -pub struct MyError { +struct MyError { name: &'static str, } // Use default implementation for `error_response()` method impl error::ResponseError for MyError {} -fn index() -> Result<&'static str, MyError> { +async fn index() -> Result<&'static str, MyError> { Err(MyError { name: "test" }) } // -pub fn main() { +#[actix_rt::main] +async fn main() -> std::io::Result<()> { use actix_web::{web, App, HttpServer}; HttpServer::new(|| App::new().route("/", web::get().to(index))) - .bind("127.0.0.1:8088") - .unwrap() + .bind("127.0.0.1:8088")? .run() - .unwrap(); + .await } diff --git a/examples/errors/src/override_error.rs b/examples/errors/src/override_error.rs index 0f354cd..ad7c786 100644 --- a/examples/errors/src/override_error.rs +++ b/examples/errors/src/override_error.rs @@ -1,6 +1,7 @@ use actix_web::{web, App}; // -use actix_web::{error, http, HttpResponse}; +use actix_http::ResponseBuilder; +use actix_web::{error, http::header, http::StatusCode, HttpResponse}; use failure::Fail; #[derive(Fail, Debug)] @@ -15,30 +16,35 @@ enum MyError { impl error::ResponseError for MyError { fn error_response(&self) -> HttpResponse { + ResponseBuilder::new(self.status_code()) + .set_header(header::CONTENT_TYPE, "text/html; charset=utf-8") + .body(self.to_string()) + } + + fn status_code(&self) -> StatusCode { match *self { - MyError::InternalError => { - HttpResponse::new(http::StatusCode::INTERNAL_SERVER_ERROR) - } - MyError::BadClientData => HttpResponse::new(http::StatusCode::BAD_REQUEST), - MyError::Timeout => HttpResponse::new(http::StatusCode::GATEWAY_TIMEOUT), + MyError::InternalError => StatusCode::INTERNAL_SERVER_ERROR, + MyError::BadClientData => StatusCode::BAD_REQUEST, + MyError::Timeout => StatusCode::GATEWAY_TIMEOUT, } } } -fn index() -> Result<&'static str, MyError> { +async fn index() -> Result<&'static str, MyError> { Err(MyError::BadClientData) } // -fn error2() -> Result<&'static str, MyError> { +async fn error2() -> Result<&'static str, MyError> { Err(MyError::InternalError) } -fn error3() -> Result<&'static str, MyError> { +async fn error3() -> Result<&'static str, MyError> { Err(MyError::Timeout) } -pub fn main() { +#[actix_rt::main] +async fn main() -> std::io::Result<()> { use actix_web::HttpServer; HttpServer::new(|| { @@ -47,8 +53,7 @@ pub fn main() { .route("/e2", web::get().to(error2)) .route("/e3", web::get().to(error3)) }) - .bind("127.0.0.1:8088") - .unwrap() + .bind("127.0.0.1:8088")? .run() - .unwrap(); + .await } diff --git a/examples/errors/src/recommend_one.rs b/examples/errors/src/recommend_one.rs index 5e8e4f2..1d42e4e 100644 --- a/examples/errors/src/recommend_one.rs +++ b/examples/errors/src/recommend_one.rs @@ -1,5 +1,6 @@ // -use actix_web::{error, http, HttpResponse}; +use actix_http::ResponseBuilder; +use actix_web::{error, http::header, http::StatusCode, HttpResponse}; use failure::Fail; #[derive(Fail, Debug)] @@ -10,26 +11,29 @@ enum UserError { impl error::ResponseError for UserError { fn error_response(&self) -> HttpResponse { + ResponseBuilder::new(self.status_code()) + .set_header(header::CONTENT_TYPE, "text/html; charset=utf-8") + .body(self.to_string()) + } + fn status_code(&self) -> StatusCode { match *self { - UserError::ValidationError { .. } => { - HttpResponse::new(http::StatusCode::BAD_REQUEST) - } + UserError::ValidationError { .. } => StatusCode::BAD_REQUEST, } } } // -fn index() -> Result<&'static str, UserError> { +async fn index() -> Result<&'static str, UserError> { Err(UserError::ValidationError { field: "bad stuff".to_string(), }) } -pub fn main() { +#[actix_rt::main] +async fn main() -> std::io::Result<()> { use actix_web::{web, App, HttpServer}; HttpServer::new(|| App::new().route("/", web::get().to(index))) - .bind("127.0.0.1:8088") - .unwrap() + .bind("127.0.0.1:8088")? .run() - .unwrap(); + .await } diff --git a/examples/errors/src/recommend_two.rs b/examples/errors/src/recommend_two.rs index cbb34de..b189428 100644 --- a/examples/errors/src/recommend_two.rs +++ b/examples/errors/src/recommend_two.rs @@ -1,5 +1,6 @@ // -use actix_web::{error, http, HttpResponse}; +use actix_http::ResponseBuilder; +use actix_web::{error, http::header, http::StatusCode, HttpResponse}; use failure::Fail; #[derive(Fail, Debug)] @@ -10,15 +11,18 @@ enum UserError { impl error::ResponseError for UserError { fn error_response(&self) -> HttpResponse { + ResponseBuilder::new(self.status_code()) + .set_header(header::CONTENT_TYPE, "text/html; charset=utf-8") + .body(self.to_string()) + } + fn status_code(&self) -> StatusCode { match *self { - UserError::InternalError => { - HttpResponse::new(http::StatusCode::INTERNAL_SERVER_ERROR) - } + UserError::InternalError => StatusCode::INTERNAL_SERVER_ERROR, } } } -fn index() -> Result<&'static str, UserError> { +async fn index() -> Result<&'static str, UserError> { do_thing_that_failes().map_err(|_e| UserError::InternalError)?; Ok("success!") } @@ -28,12 +32,12 @@ fn do_thing_that_failes() -> Result<(), std::io::Error> { Err(std::io::Error::new(std::io::ErrorKind::Other, "some error")) } -pub fn main() { +#[actix_rt::main] +async fn main() -> std::io::Result<()> { use actix_web::{web, App, HttpServer}; HttpServer::new(|| App::new().route("/", web::get().to(index))) - .bind("127.0.0.1:8088") - .unwrap() + .bind("127.0.0.1:8088")? .run() - .unwrap(); + .await } diff --git a/examples/extractors/Cargo.toml b/examples/extractors/Cargo.toml index 0e31c27..8cc6c12 100644 --- a/examples/extractors/Cargo.toml +++ b/examples/extractors/Cargo.toml @@ -4,7 +4,8 @@ version = "1.0.0" edition = "2018" [dependencies] -actix-web = "1.0" +actix-web = "2.0" +actix-rt = "1.0" serde = "1.0" -futures = "0.1" +futures = "0.3" serde_json = "1.0" diff --git a/examples/extractors/src/form.rs b/examples/extractors/src/form.rs index daf58cf..43dc763 100644 --- a/examples/extractors/src/form.rs +++ b/examples/extractors/src/form.rs @@ -10,17 +10,17 @@ struct FormData { /// extract form data using serde /// this handler gets called only if the content type is *x-www-form-urlencoded* /// and the content of the request could be deserialized to a `FormData` struct -fn index(form: web::Form) -> Result { +async fn index(form: web::Form) -> Result { Ok(format!("Welcome {}!", form.username)) } // -pub fn main() { +#[actix_rt::main] +async fn main() -> std::io::Result<()> { use actix_web::{App, HttpServer}; HttpServer::new(|| App::new().route("/", web::post().to(index))) - .bind("127.0.0.1:8088") - .unwrap() + .bind("127.0.0.1:8088")? .run() - .unwrap(); + .await } diff --git a/examples/extractors/src/json_one.rs b/examples/extractors/src/json_one.rs index d1600ce..b5c2675 100644 --- a/examples/extractors/src/json_one.rs +++ b/examples/extractors/src/json_one.rs @@ -8,17 +8,17 @@ struct Info { } /// deserialize `Info` from request's body -fn index(info: web::Json) -> Result { +async fn index(info: web::Json) -> Result { Ok(format!("Welcome {}!", info.username)) } // -pub fn main() { +#[actix_rt::main] +async fn main() -> std::io::Result<()> { use actix_web::{App, HttpServer}; HttpServer::new(|| App::new().route("/", web::post().to(index))) - .bind("127.0.0.1:8088") - .unwrap() + .bind("127.0.0.1:8088")? .run() - .unwrap(); + .await } diff --git a/examples/extractors/src/json_two.rs b/examples/extractors/src/json_two.rs index a61a6cf..a619655 100644 --- a/examples/extractors/src/json_two.rs +++ b/examples/extractors/src/json_two.rs @@ -8,11 +8,12 @@ struct Info { } /// deserialize `Info` from request's body, max payload size is 4kb -fn index(info: web::Json) -> impl Responder { +async fn index(info: web::Json) -> impl Responder { format!("Welcome {}!", info.username) } -pub fn main() { +#[actix_rt::main] +async fn main() -> std::io::Result<()> { use actix_web::{App, HttpServer}; HttpServer::new(|| { @@ -34,9 +35,8 @@ pub fn main() { .route(web::post().to(index)), ) }) - .bind("127.0.0.1:8088") - .unwrap() + .bind("127.0.0.1:8088")? .run() - .unwrap(); + .await } // diff --git a/examples/extractors/src/main.rs b/examples/extractors/src/main.rs index 0925a79..07f40a2 100644 --- a/examples/extractors/src/main.rs +++ b/examples/extractors/src/main.rs @@ -1,5 +1,4 @@ use actix_web::{web, App, FromRequest, HttpRequest, HttpServer, Responder}; -use futures::future::Future; use serde::Deserialize; // pub mod custom_handler; @@ -19,31 +18,34 @@ struct MyInfo { } // -fn index(path: web::Path<(String, String)>, json: web::Json) -> impl Responder { +async fn index( + path: web::Path<(String, String)>, + json: web::Json, +) -> impl Responder { format!("{} {} {} {}", path.0, path.1, json.id, json.username) } // // -fn extract(req: HttpRequest) -> impl Responder { - let params = web::Path::<(String, String)>::extract(&req).unwrap(); +async fn extract(req: HttpRequest) -> impl Responder { + let params = web::Path::<(String, String)>::extract(&req).await.unwrap(); let info = web::Json::::extract(&req) - .wait() + .await .expect("Err with reading json."); format!("{} {} {} {}", params.0, params.1, info.username, info.id) } // -fn main() { +#[actix_rt::main] +async fn main() -> std::io::Result<()> { HttpServer::new(|| { App::new() .route("/{name}/{id}", web::post().to(index)) .route("/{name}/{id}/extract", web::post().to(extract)) }) - .bind("127.0.0.1:8088") - .unwrap() + .bind("127.0.0.1:8088")? .run() - .unwrap(); + .await } diff --git a/examples/extractors/src/multiple.rs b/examples/extractors/src/multiple.rs index 31411a7..2a1cc09 100644 --- a/examples/extractors/src/multiple.rs +++ b/examples/extractors/src/multiple.rs @@ -7,14 +7,15 @@ struct Info { username: String, } -fn index((path, query): (web::Path<(u32, String)>, web::Query)) -> String { +async fn index((path, query): (web::Path<(u32, String)>, web::Query)) -> String { format!( "Welcome {}, friend {}, userid {}!", query.username, path.1, path.0 ) } -pub fn main() { +#[actix_rt::main] +async fn main() -> std::io::Result<()> { use actix_web::{App, HttpServer}; HttpServer::new(|| { @@ -23,9 +24,8 @@ pub fn main() { web::get().to(index), ) }) - .bind("127.0.0.1:8088") - .unwrap() + .bind("127.0.0.1:8088")? .run() - .unwrap(); + .await } // diff --git a/examples/extractors/src/path_one.rs b/examples/extractors/src/path_one.rs index 1440b8e..a378ba2 100644 --- a/examples/extractors/src/path_one.rs +++ b/examples/extractors/src/path_one.rs @@ -4,11 +4,12 @@ use actix_web::{web, Result}; /// extract path info from "/users/{userid}/{friend}" url /// {userid} - - deserializes to a u32 /// {friend} - deserializes to a String -fn index(info: web::Path<(u32, String)>) -> Result { +async fn index(info: web::Path<(u32, String)>) -> Result { Ok(format!("Welcome {}, userid {}!", info.1, info.0)) } -pub fn main() { +#[actix_rt::main] +async fn main() -> std::io::Result<()> { use actix_web::{App, HttpServer}; HttpServer::new(|| { @@ -17,9 +18,8 @@ pub fn main() { web::get().to(index), ) }) - .bind("127.0.0.1:8088") - .unwrap() + .bind("127.0.0.1:8088")? .run() - .unwrap(); + .await } // diff --git a/examples/extractors/src/path_three.rs b/examples/extractors/src/path_three.rs index 68badaa..98484c5 100644 --- a/examples/extractors/src/path_three.rs +++ b/examples/extractors/src/path_three.rs @@ -1,14 +1,15 @@ use actix_web::{web, HttpRequest, Result}; // -fn index(req: HttpRequest) -> Result { +async fn index(req: HttpRequest) -> Result { let name: String = req.match_info().get("friend").unwrap().parse().unwrap(); let userid: i32 = req.match_info().query("userid").parse().unwrap(); Ok(format!("Welcome {}, userid {}!", name, userid)) } -pub fn main() { +#[actix_rt::main] +async fn main() -> std::io::Result<()> { use actix_web::{App, HttpServer}; HttpServer::new(|| { @@ -17,9 +18,8 @@ pub fn main() { web::get().to(index), ) }) - .bind("127.0.0.1:8088") - .unwrap() + .bind("127.0.0.1:8088")? .run() - .unwrap(); + .await } // diff --git a/examples/extractors/src/path_two.rs b/examples/extractors/src/path_two.rs index ee5e357..764ddfe 100644 --- a/examples/extractors/src/path_two.rs +++ b/examples/extractors/src/path_two.rs @@ -9,11 +9,12 @@ struct Info { } /// extract path info using serde -fn index(info: web::Path) -> Result { +async fn index(info: web::Path) -> Result { Ok(format!("Welcome {}, userid {}!", info.friend, info.userid)) } -pub fn main() { +#[actix_rt::main] +async fn main() -> std::io::Result<()> { use actix_web::{App, HttpServer}; HttpServer::new(|| { @@ -22,9 +23,8 @@ pub fn main() { web::get().to(index), ) }) - .bind("127.0.0.1:8088") - .unwrap() + .bind("127.0.0.1:8088")? .run() - .unwrap(); + .await } // diff --git a/examples/extractors/src/query.rs b/examples/extractors/src/query.rs index 74575ab..23d4480 100644 --- a/examples/extractors/src/query.rs +++ b/examples/extractors/src/query.rs @@ -8,17 +8,17 @@ struct Info { } // this handler get called only if the request's query contains `username` field -fn index(info: web::Query) -> String { +async fn index(info: web::Query) -> String { format!("Welcome {}!", info.username) } // -pub fn main() { +#[actix_rt::main] +async fn main() -> std::io::Result<()> { use actix_web::{App, HttpServer}; HttpServer::new(|| App::new().route("/", web::get().to(index))) - .bind("127.0.0.1:8088") - .unwrap() + .bind("127.0.0.1:8088")? .run() - .unwrap(); + .await }