warp app to test multithreading.

This commit is contained in:
Bill Thiede 2020-04-03 21:41:16 -07:00
commit fddf995996
4 changed files with 1424 additions and 0 deletions

1
.gitignore vendored Normal file
View File

@ -0,0 +1 @@
/target

1356
Cargo.lock generated Normal file

File diff suppressed because it is too large Load Diff

12
Cargo.toml Normal file
View File

@ -0,0 +1,12 @@
[package]
name = "warptest"
version = "0.1.0"
authors = ["Bill Thiede <git@xinu.tv>"]
edition = "2018"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
warp = "0.2.2"
tokio = { version = "0.2", features = ["macros"] }
stderrlog = "0.4.3"

55
src/main.rs Normal file
View File

@ -0,0 +1,55 @@
//#![deny(warnings)]
use std::convert::Infallible;
use std::str::FromStr;
use std::time::{Duration, Instant};
use warp::Filter;
#[tokio::main]
async fn main() {
// Setup logging
stderrlog::new()
.verbosity(2)
.timestamp(stderrlog::Timestamp::Millisecond)
.init()
.unwrap();
// Match `/sleep/:Seconds`...
// and_then create a `Future` that will simply wait N seconds...
let sleepy = warp::path("sleep")
.and(warp::path::param())
.and_then(sleepy);
// Match `/spin/:Seconds`... and burn CPU for N seconds...
let spin = warp::path("spin").and(warp::path::param()).and_then(spin);
let index = warp::any().map(|| {
warp::http::Response::builder()
.header("content-type", "text/html; charset=utf-8")
.body(
r#"<!DOCTYPE html><title>warp test</title><body>
<div><a href="/spin/5">Spin for 5 seconds</a></div>
<div><a href="/sleep/5">Sleep for 5 seconds</a></div>
"#,
)
});
let routes = sleepy.or(spin).or(index);
let routes = routes.with(warp::log("warptest"));
println!("Listening on :3030");
warp::serve(routes).run(([0, 0, 0, 0], 3030)).await;
}
async fn spin(seconds: u64) -> Result<impl warp::Reply, Infallible> {
let end = Instant::now() + Duration::new(seconds, 0);
let mut cnt = 0;
loop {
cnt += 1;
if Instant::now() > end {
return Ok(format!("I spun {} times in {} seconds!", cnt, seconds));
}
}
}
async fn sleepy(seconds: u64) -> Result<impl warp::Reply, Infallible> {
tokio::time::delay_for(Duration::from_secs(seconds)).await;
Ok(format!("I waited {} seconds!", seconds))
}