From 161a042123831cd5c0100d3790339deb35599428 Mon Sep 17 00:00:00 2001 From: Jared Burce Date: Wed, 18 Mar 2020 17:13:05 -0700 Subject: [PATCH] Handle POST requests --- Cargo.toml | 1 + src/main.rs | 47 ++++++++++++++++++++++++++++++++++++++++++----- static/index.html | 8 ++++++-- 3 files changed, 49 insertions(+), 7 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 49540df..9ff9574 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -6,6 +6,7 @@ edition = "2018" [dependencies] futures = "0.3" +log = "0.4" pretty_env_logger = "0.4" tokio = { version = "0.2", features = ["macros"] } warp = "0.2" diff --git a/src/main.rs b/src/main.rs index d0c95ca..5d52486 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,14 +1,51 @@ -use warp::Filter; +use std::collections::HashMap; -#[tokio::main(basic_scheduler)] +use log::info; +use warp::{Filter, Rejection, Reply}; +use warp::http::StatusCode; + +#[tokio::main] async fn main() { pretty_env_logger::init(); - let root = warp::get() - .and(warp::path::end()) + // GET / + let root = warp::path::end() + .and(warp::get()) .and(warp::fs::file("./static/index.html")); - let routes = root; + // POST /name name={name} + let namechange = warp::path("name") + .and(warp::path::end()) + .and(warp::post()) + .and(warp::body::content_length_limit(1024 * 16)) + .and(warp::body::form()) + .and_then(|form: HashMap| async move { + let name = match form.get("name") { + None => return Err(warp::reject::custom(BadName)), + Some(name) if name.is_empty() || + name.chars().count() > 32 => return Err(warp::reject::custom(BadName)), + Some(name) => name + }; + info!("POST /name as \"{}\"", name); + Ok(warp::reply::with_header(StatusCode::SEE_OTHER, + warp::http::header::LOCATION, + "/")) + }) + .recover(handle_reject); + + let routes = root + .or(namechange); warp::serve(routes).run(([127, 0, 0, 1], 8060)).await; } + +#[derive(Debug)] +struct BadName; +impl warp::reject::Reject for BadName {} + +async fn handle_reject(err: Rejection) -> Result { + match err.find() { + Some(BadName) => Ok(warp::reply::with_status(warp::reply(), StatusCode::BAD_REQUEST)), + _ => Err(err) + } +} diff --git a/static/index.html b/static/index.html index aef9406..6a0f3ca 100644 --- a/static/index.html +++ b/static/index.html @@ -1,9 +1,13 @@ - + + Hello, World! - Hello, Warp! +
+ + +