Skip to content
Permalink
Browse files

convert to use await

  • Loading branch information
alsuren committed Nov 17, 2019
1 parent dded525 commit ec1340cb4416554611a88bdeed5fb7796c66e942
@@ -60,6 +60,7 @@ members = [
"examples/handlers/simple_async_handlers_await",
"examples/handlers/async_handlers",
"examples/handlers/form_urlencoded",
"examples/handlers/form_urlencoded_await",
"examples/handlers/multipart",

# static_assets
@@ -1,14 +1,20 @@
[package]
name = "gotham_examples_handlers_form_urlencoded"
name = "gotham_examples_handlers_form_urlencoded_await"
description = "An example of decoding requests from an HTML form element"
version = "0.0.0"
authors = ["Jacob Budin <self@jacobbudin.com>"]
publish = false
edition = "2018"

[dependencies]
gotham = { path = "../../../gotham" }

hyper = "0.12"
mime = "0.3"
futures = "0.1"
# We need two versions of the futures library. One that matches what Gotham
# understands, and one that matches what .await understands. Stolen from:
# https://rust-lang-nursery.github.io/futures-rs/blog/2019/04/18/compatibility-layer.html
# (although they call the old version futures01 and we call it legacy_futures)
legacy_futures = {package = "futures", version = "0.1"}
futures = {package = "futures", version = "0.3.1", features = ["compat"]}
url = "2.1"
@@ -6,8 +6,10 @@ extern crate hyper;
extern crate mime;
extern crate url;

use futures::{future, Future, Stream};
use futures::compat::Future01CompatExt;
use futures::{FutureExt, TryFutureExt};
use hyper::{Body, StatusCode};
use legacy_futures::Stream;
use url::form_urlencoded;

use gotham::handler::{HandlerFuture, IntoHandlerError};
@@ -18,9 +20,10 @@ use gotham::state::{FromState, State};

/// Extracts the elements of the POST request and responds with the form keys and values
fn form_handler(mut state: State) -> Box<HandlerFuture> {
let f = Body::take_from(&mut state)
.concat2()
.then(|full_body| match full_body {
let f = async {
let full_body = Body::take_from(&mut state).concat2().compat().await;

match full_body {
Ok(valid_body) => {
let body_content = valid_body.into_bytes();
// Perform decoding on request body
@@ -32,12 +35,12 @@ fn form_handler(mut state: State) -> Box<HandlerFuture> {
res_body.push_str(&res_body_line);
}
let res = create_response(&state, StatusCode::OK, mime::TEXT_PLAIN, res_body);
future::ok((state, res))
Ok((state, res))
}
Err(e) => future::err((state, e.into_handler_error())),
});

Box::new(f)
Err(e) => Err((state, e.into_handler_error())),
}
};
Box::new(f.boxed().compat())
}

/// Create a `Router`

0 comments on commit ec1340c

Please sign in to comment.
You can’t perform that action at this time.