Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rofrol/351f97c40ebc83c20882c2859db8c626 to your computer and use it in GitHub Desktop.
Save rofrol/351f97c40ebc83c20882c2859db8c626 to your computer and use it in GitHub Desktop.
migration_from_actix-web-0.7.19_to_1.0.0-beta.5.md
diff --git a/mock/server/src/main.rs b/mock/server/src/main.rs
index 91dbf9c7..f53b9dd6 100644
--- a/mock/server/src/main.rs
+++ b/mock/server/src/main.rs
@@ -1,4 +1,3 @@
-extern crate actix;
extern crate actix_web;
extern crate bytes;
extern crate env_logger;
@@ -15,8 +14,8 @@ use std::collections::BTreeMap as Map;
use futures::{future::ok as fut_ok, Future};

use actix_web::{
-    client, http, middleware, middleware::cors::Cors, server, App, AsyncResponder, FromRequest,
-    HttpMessage, HttpRequest, HttpResponse, Path,
+    client::Client, middleware, middleware::cors::Cors, web, App, FromRequest, HttpRequest,
+    HttpResponse, HttpServer, Responder,
};

use bytes::Bytes;
@@ -162,49 +161,44 @@ struct QuestionsResponse {
   data: Vec<Question>,
}

-fn q(req: &HttpRequest) -> Box<Future<Item = HttpResponse, Error = actix_web::error::Error>> {
-    req.json()
-        .from_err() // convert all errors into `Error`
-        .and_then(|_val: RequestObj| {
-            use std::fs;
-            let j = fs::read_to_string("json/response_q.json").unwrap();
+// test with: curl -d '<json>' -H "Content-Type: application/json" -X POST http://localhost:8080/v2/q
+fn q(_val: web::Json<RequestObj>) -> impl Responder {
+    use std::fs;
+    let j = fs::read_to_string("json/response_q.json").unwrap();

-            Ok(HttpResponse::Ok().content_type("application/json").body(j)) // <- send response
-        })
-        .responder()
+    HttpResponse::Ok().content_type("application/json").body(j) // <- send response
}

-fn questions_data() -> Box<Future<Item = Vec<Question>, Error = actix_web::error::Error>> {
+fn questions_data(
+    client: &Client,
+) -> impl Future<Item = Vec<Question>, Error = actix_web::error::Error> {
   let f = std::fs::read_to_string("auth_token").unwrap();
   let token = f.trim();
-    Box::new(
-        client::ClientRequest::get("http://localhost:8081/api/questions")
-            .header(
-                actix_web::http::header::AUTHORIZATION,
-                "Bearer ".to_owned() + token,
-            )
-            .finish()
-            .unwrap()
-            .send()
-            .timeout(Duration::from_secs(30))
-            .map_err(actix_web::error::Error::from) // <- convert SendRequestError to an Error
-            .and_then(|resp| {
-                resp.body().limit(67_108_864).from_err().and_then(|body| {
-                    let resp: QuestionsResponse = serde_json::from_slice(&body).unwrap();
-                    fut_ok(resp.data)
-                })
-            }),
-    )
+    client
+        .get("http://localhost:8081/api/questions")
+        .header(
+            actix_web::http::header::AUTHORIZATION,
+            "Bearer ".to_owned() + token,
+        )
+        .timeout(Duration::from_secs(30))
+        .send()
+        .map_err(actix_web::error::Error::from) // <- convert SendRequestError to an Error
+        .and_then(|mut resp| {
+            resp.body().limit(67_108_864).from_err().and_then(|body| {
+                let resp: QuestionsResponse = serde_json::from_slice(&body).unwrap();
+                fut_ok(resp.data)
+            })
+        })
}

-fn questions(_: &HttpRequest) -> Box<Future<Item = HttpResponse, Error = actix_web::error::Error>> {
-    questions_data()
-        .and_then(|d| {
-            Ok(HttpResponse::Ok()
-                .content_type("application/json")
-                .body(serde_json::to_string(&d).unwrap()))
-        })
-        .responder()
+fn questions(
+    client: web::Data<Client>,
+) -> impl Future<Item = HttpResponse, Error = actix_web::error::Error> {
+    questions_data(&client).and_then(|d| {
+        Ok(HttpResponse::Ok()
+            .content_type("application/json")
+            .body(serde_json::to_string(&d).unwrap()))
+    })
}

#[derive(Deserialize)]
@@ -232,29 +226,31 @@ struct Campaign {

fn question_data(
   id: &str,
-    token: actix_web::http::header::HeaderValue,
-) -> Box<Future<Item = Bytes, Error = actix_web::error::Error>> {
-    Box::new(
-        client::ClientRequest::get(format!(
+    token: &actix_web::http::header::HeaderValue,
+    client: &Client,
+) -> impl Future<Item = Bytes, Error = actix_web::error::Error> {
+    client
+        .get(format!(
           "http://localhost:8081/api/questions/{}",
           id
       ))
-        .header(actix_web::http::header::AUTHORIZATION, token)
-        .finish()
-        .unwrap()
-        .send()
+        .header(actix_web::http::header::AUTHORIZATION, token.clone())
       .timeout(Duration::from_secs(30))
+        .send()
       .map_err(actix_web::error::Error::from) // <- convert SendRequestError to an Error
-        .and_then(|resp| resp.body().limit(67_108_864).from_err()),
-    )
+        .and_then(|mut resp| resp.body().limit(67_108_864).from_err())
}

fn campaign(
-    req: &HttpRequest,
-) -> Box<Future<Item = HttpResponse, Error = actix_web::error::Error>> {
+    req: HttpRequest,
+    client: web::Data<Client>,
+) -> impl Future<Item = HttpResponse, Error = actix_web::error::Error> {
   use std::fs;
-    let token = req.headers()[actix_web::http::header::AUTHORIZATION].clone();
-    let params = Path::<CampaignParams>::extract(req).unwrap();
+    let token = req
+        .headers()
+        .get(actix_web::http::header::AUTHORIZATION)
+        .unwrap();
+    let params = web::Path::<CampaignParams>::extract(&req).unwrap();
   let c = fs::read_to_string("json/campaigns/".to_owned() + &params.id + ".json").unwrap();
   let campaign_temp = serde_json::from_str::<CampaignTemp>(&c).unwrap();

@@ -264,7 +260,7 @@ fn campaign(
       .iter()
       .map(|question| question.id.clone())
       .collect();
-    let futures = ids.iter().map(|id| question_data(id, token.clone()));
+    let futures = ids.iter().map(|id| question_data(id, &token, &client));
   futures::stream::futures_unordered(futures)
       .map(|body| {
           let resp: QuestionData = serde_json::from_slice(&body).unwrap();
@@ -328,27 +324,20 @@ fn campaign(
               .content_type("application/json")
               .body(campaign_json))
       })
-        .responder()
}

fn main() -> Result<(), Box<std::error::Error>> {
   ::std::env::set_var("RUST_LOG", "actix_web=info");
   env_logger::init();
-    let sys = actix::System::new("campaigns mock server");
+    let sys = actix_rt::System::new("campaigns mock server");

-    server::new(|| {
+    HttpServer::new(|| {
       App::new()
-            .middleware(middleware::Logger::default())
-            .configure(|app| {
-                Cors::for_app(app)
-                    .send_wildcard()
-                    .resource("/v2/q", |r| r.method(http::Method::POST).f(q))
-                    .resource("/campaigns/{id}", |r| {
-                        r.method(http::Method::GET).f(campaign)
-                    })
-                    .resource("/questions", |r| r.method(http::Method::GET).f(questions))
-                    .register()
-            })
+            .wrap(middleware::Logger::default())
+            .wrap(Cors::new().send_wildcard())
+            .service(web::resource("/v2/q").to(q))
+            .service(web::resource("/questions").route(web::get().to_async(questions)))
+            .service(web::resource("/campaigns/{id}").route(web::get().to_async(campaign)))
   })
   .bind("127.0.0.1:8080")
   .unwrap()
@@ -455,14 +444,13 @@ mod tests {
   }
diff --git a/mock/server/Cargo.toml b/mock/server/Cargo.toml
index d24b424b..f3701532 100644
--- a/mock/server/Cargo.toml
+++ b/mock/server/Cargo.toml
@@ -4,9 +4,9 @@ version = "0.1.0"
authors = ["Roman Frołow <rofrol@gmail.com>"]

[dependencies]
-actix-web = { version="0.7.3", features=["rust-tls"] }
-actix = "0.7.5"
-env_logger = "0.5.13"
+actix-rt = "0.2"
+actix-web = { version="1.0.0-beta.5", features=["rust-tls"] }
+env_logger = "0.6.1"
futures = "0.1.25"
serde = "1.0.80"
serde_derive = "1.0.80"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment