Skip to content

Commit

Permalink
update to std::future::Future (#265)
Browse files Browse the repository at this point in the history
* update to rust 2018 edition

* update to std::future::Future
  • Loading branch information
jxs committed Oct 24, 2019
1 parent 9eb4bb4 commit 5c26956
Show file tree
Hide file tree
Showing 71 changed files with 2,185 additions and 1,877 deletions.
20 changes: 11 additions & 9 deletions Cargo.toml
Expand Up @@ -11,13 +11,18 @@ categories = ["web-programming::http-server"]
keywords = ["warp", "server", "http", "hyper"]
autotests = true
autoexamples = true
edition = "2018"

[package.metadata.docs.rs]
features = ["tls"]

[dependencies]
bytes = "0.4.8"
futures = "0.1"
futures-preview = "0.3.0-alpha.19"
futures-util-preview = "0.3.0-alpha.19"
headers = "0.2"
http = "0.1"
hyper = "0.12.18"
hyper = { version = "=0.13.0-alpha.4", features = ["unstable-stream"] }
log = "0.4"
mime = "0.3"
mime_guess = "2.0.0"
Expand All @@ -26,13 +31,13 @@ scoped-tls = "1.0"
serde = "1.0"
serde_json = "1.0"
serde_urlencoded = "0.6"
tokio = "0.1.11"
tokio-io = "0.1"
rustls = { version = "0.15", optional = true }
tokio-threadpool = "0.1.7"
tokio = "0.2.0-alpha.6"
tokio-executor = "=0.2.0-alpha.6"
rustls = { version = "0.16", optional = true }
# tls is enabled by default, we don't want that yet
tungstenite = { default-features = false, version = "0.9", optional = true }
urlencoding = "1.0.0"
pin-project = "0.4.5"

[dev-dependencies]
pretty_env_logger = "0.3"
Expand All @@ -44,9 +49,6 @@ default = ["multipart", "websocket"]
websocket = ["tungstenite"]
tls = ["rustls"]

[package.metadata.docs.rs]
features = ["tls"]

[profile.release]
codegen-units = 1
incremental = false
Expand Down
12 changes: 5 additions & 7 deletions examples/body.rs
@@ -1,9 +1,6 @@
#![deny(warnings)]
extern crate serde;
#[macro_use]
extern crate serde_derive;
extern crate pretty_env_logger;
extern crate warp;

use serde_derive::{Deserialize, Serialize};

use warp::Filter;

Expand All @@ -13,7 +10,8 @@ struct Employee {
rate: u32,
}

fn main() {
#[tokio::main]
async fn main() {
pretty_env_logger::init();

// POST /employees/:rate {"name":"Sean","rate":2}
Expand All @@ -28,5 +26,5 @@ fn main() {
warp::reply::json(&employee)
});

warp::serve(promote).run(([127, 0, 0, 1], 3030));
warp::serve(promote).run(([127, 0, 0, 1], 3030)).await
}
7 changes: 3 additions & 4 deletions examples/dir.rs
@@ -1,9 +1,8 @@
#![deny(warnings)]
extern crate pretty_env_logger;
extern crate warp;

fn main() {
#[tokio::main]
async fn main() {
pretty_env_logger::init();

warp::serve(warp::fs::dir("examples/dir")).run(([127, 0, 0, 1], 3030));
warp::serve(warp::fs::dir("examples/dir")).run(([127, 0, 0, 1], 3030)).await;
}
72 changes: 36 additions & 36 deletions examples/errors.rs
@@ -1,15 +1,11 @@
#![deny(warnings)]
extern crate serde;
#[macro_use]
extern crate serde_derive;
extern crate pretty_env_logger;
extern crate warp;

use std::error::Error as StdError;
use std::fmt::{self, Display};

use serde_derive::Serialize;
use warp::http::StatusCode;
use warp::{Filter, Rejection, Reply};
use warp::{Future, Filter, Rejection, Reply};

#[derive(Copy, Clone, Debug)]
enum Error {
Expand All @@ -34,49 +30,53 @@ impl Display for Error {

impl StdError for Error {}

fn main() {
#[tokio::main]
async fn main() {
let hello = warp::path::end().map(warp::reply);

let oops =
warp::path("oops").and_then(|| Err::<StatusCode, _>(warp::reject::custom(Error::Oops)));
warp::path("oops").and_then(|| futures::future::err::<StatusCode, _>(warp::reject::custom(Error::Oops)));

let nope =
warp::path("nope").and_then(|| Err::<StatusCode, _>(warp::reject::custom(Error::Nope)));
warp::path("nope").and_then(|| futures::future::err::<StatusCode, _>(warp::reject::custom(Error::Nope)));

let routes = warp::get2()
.and(hello.or(oops).or(nope))
.recover(customize_error);

warp::serve(routes).run(([127, 0, 0, 1], 3030));
warp::serve(routes).run(([127, 0, 0, 1], 3030)).await;
}

// This function receives a `Rejection` and tries to return a custom
// value, othewise simply passes the rejection along.
fn customize_error(err: Rejection) -> Result<impl Reply, Rejection> {
if let Some(&err) = err.find_cause::<Error>() {
let code = match err {
Error::Nope => StatusCode::BAD_REQUEST,
Error::Oops => StatusCode::INTERNAL_SERVER_ERROR,
};
let msg = err.to_string();
fn customize_error(err: Rejection) -> impl Future< Output = Result<impl Reply, Rejection>> {
let err = {
if let Some(&err) = err.find_cause::<Error>() {
let code = match err {
Error::Nope => StatusCode::BAD_REQUEST,
Error::Oops => StatusCode::INTERNAL_SERVER_ERROR,
};
let msg = err.to_string();

let json = warp::reply::json(&ErrorMessage {
code: code.as_u16(),
message: msg,
});
Ok(warp::reply::with_status(json, code))
} else if let Some(_) = err.find_cause::<warp::reject::MethodNotAllowed>() {
// We can handle a specific error, here METHOD_NOT_ALLOWED,
// and render it however we want
let code = StatusCode::METHOD_NOT_ALLOWED;
let json = warp::reply::json(&ErrorMessage {
code: code.as_u16(),
message: "oops, you aren't allowed to use this method.".into(),
});
Ok(warp::reply::with_status(json, code))
} else {
// Could be a NOT_FOUND, or any other internal error... here we just
// let warp use its default rendering.
Err(err)
}
let json = warp::reply::json(&ErrorMessage {
code: code.as_u16(),
message: msg,
});
Ok(warp::reply::with_status(json, code))
} else if let Some(_) = err.find_cause::<warp::reject::MethodNotAllowed>() {
// We can handle a specific error, here METHOD_NOT_ALLOWED,
// and render it however we want
let code = StatusCode::METHOD_NOT_ALLOWED;
let json = warp::reply::json(&ErrorMessage {
code: code.as_u16(),
message: "oops, you aren't allowed to use this method.".into(),
});
Ok(warp::reply::with_status(json, code))
} else {
// Could be a NOT_FOUND, or any other internal error... here we just
// let warp use its default rendering.
Err(err)
}
};
futures::future::ready(err)
}
7 changes: 3 additions & 4 deletions examples/file.rs
@@ -1,10 +1,9 @@
#![deny(warnings)]
extern crate pretty_env_logger;
extern crate warp;

use warp::Filter;

fn main() {
#[tokio::main]
async fn main() {
pretty_env_logger::init();

let readme = warp::get2()
Expand All @@ -18,5 +17,5 @@ fn main() {
// GET /ex/... => ./examples/..
let routes = readme.or(examples);

warp::serve(routes).run(([127, 0, 0, 1], 3030));
warp::serve(routes).run(([127, 0, 0, 1], 3030)).await;
}
26 changes: 9 additions & 17 deletions examples/futures.rs
@@ -1,11 +1,9 @@
#![deny(warnings)]
extern crate tokio;
extern crate warp;

use std::str::FromStr;
use std::time::{Duration, Instant};
use tokio::timer::Delay;
use warp::{Filter, Future};
use tokio::timer::delay;
use warp::Filter;

/// A newtype to enforce our maximum allowed seconds.
struct Seconds(u64);
Expand All @@ -23,21 +21,15 @@ impl FromStr for Seconds {
}
}

fn main() {
#[tokio::main]
async fn main() {
// Match `/:u32`...
let routes = warp::path::param()
// and_then create a `Future` that will simply wait N seconds...
.and_then(|Seconds(seconds)| {
Delay::new(Instant::now() + Duration::from_secs(seconds))
// return the number of seconds again...
.map(move |()| seconds)
// An error from `Delay` means a big problem with the server...
.map_err(|timer_err| {
eprintln!("timer error: {}", timer_err);
warp::reject::custom(timer_err)
})
})
.map(|seconds| format!("I waited {} seconds!", seconds));
.and_then(|Seconds(seconds): Seconds| async move {
delay(Instant::now() + Duration::from_secs(seconds)).await;
Ok::<String, warp::Rejection>(format!("I waited {} seconds!", seconds))
});

warp::serve(routes).run(([127, 0, 0, 1], 3030));
warp::serve(routes).run(([127, 0, 0, 1], 3030)).await;
}
13 changes: 4 additions & 9 deletions examples/handlebars_template.rs
@@ -1,15 +1,9 @@
#![deny(warnings)]
extern crate handlebars;
extern crate hyper;
extern crate warp;
#[macro_use]
extern crate serde_json;
extern crate serde;

use std::error::Error;
use std::sync::Arc;

use handlebars::Handlebars;
use serde_json::json;
use serde::Serialize;
use warp::Filter;

Expand All @@ -26,7 +20,8 @@ where
.unwrap_or_else(|err| err.description().to_owned())
}

fn main() {
#[tokio::main]
async fn main() {
let template = "<!DOCTYPE html>
<html>
<head>
Expand Down Expand Up @@ -58,5 +53,5 @@ fn main() {
})
.map(handlebars);

warp::serve(route).run(([127, 0, 0, 1], 3030));
warp::serve(route).run(([127, 0, 0, 1], 3030)).await;
}
8 changes: 3 additions & 5 deletions examples/headers.rs
@@ -1,7 +1,4 @@
#![deny(warnings)]
extern crate pretty_env_logger;
extern crate warp;

use std::net::SocketAddr;
use warp::Filter;

Expand All @@ -11,7 +8,8 @@ use warp::Filter;
/// - `Accept` is exactly `*/*`
///
/// If these conditions don't match, a 404 is returned.
fn main() {
#[tokio::main]
async fn main() {
pretty_env_logger::init();

// For this example, we assume no DNS was used,
Expand All @@ -25,5 +23,5 @@ fn main() {
.and(accept_stars)
.map(|addr| format!("accepting stars on {}", addr));

warp::serve(routes).run(([127, 0, 0, 1], 3030));
warp::serve(routes).run(([127, 0, 0, 1], 3030)).await;
}
7 changes: 3 additions & 4 deletions examples/hello.rs
@@ -1,11 +1,10 @@
#![deny(warnings)]
extern crate warp;

use warp::Filter;

fn main() {
#[tokio::main]
async fn main() {
// Match any request and return hello world!
let routes = warp::any().map(|| "Hello, World!");

warp::serve(routes).run(([127, 0, 0, 1], 3030));
warp::serve(routes).run(([127, 0, 0, 1], 3030)).await;
}
7 changes: 3 additions & 4 deletions examples/returning.rs
@@ -1,5 +1,3 @@
extern crate warp;

use warp::{filters::BoxedFilter, Filter, Rejection, Reply};

// Option 1: BoxedFilter
Expand All @@ -15,7 +13,8 @@ pub fn index_filter() -> impl Filter<Extract = (&'static str,), Error = Rejectio
warp::path::end().map(|| "Index page")
}

pub fn main() {
#[tokio::main]
async fn main() {
let routes = index_filter().or(assets_filter());
warp::serve(routes).run(([127, 0, 0, 1], 3030));
warp::serve(routes).run(([127, 0, 0, 1], 3030)).await;
}
6 changes: 3 additions & 3 deletions examples/routing.rs
@@ -1,11 +1,11 @@
#![deny(warnings)]
extern crate pretty_env_logger;
#[macro_use]
extern crate warp;

use warp::Filter;

fn main() {
#[tokio::main]
async fn main() {
pretty_env_logger::init();

// We'll start simple, and gradually show how you combine these powers
Expand Down Expand Up @@ -89,5 +89,5 @@ fn main() {
// If you wish to use dynamic dispatch instead and speed up compile times while
// making it slightly slower at runtime, you can use Filter::boxed().

warp::serve(routes).run(([127, 0, 0, 1], 3030));
warp::serve(routes).run(([127, 0, 0, 1], 3030)).await;
}

0 comments on commit 5c26956

Please sign in to comment.