Handle POST requests
This commit is contained in:
@@ -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"
|
||||
|
||||
47
src/main.rs
47
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<String, String>| 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<impl Reply, Rejection> {
|
||||
match err.find() {
|
||||
Some(BadName) => Ok(warp::reply::with_status(warp::reply(), StatusCode::BAD_REQUEST)),
|
||||
_ => Err(err)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,9 +1,13 @@
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
|
||||
<title>Hello, World!</title>
|
||||
</head>
|
||||
<body>
|
||||
Hello, Warp!
|
||||
<form action="name" method="post">
|
||||
<input name="name" type="text">
|
||||
<input type="submit" value="Set Name">
|
||||
</form>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
Reference in New Issue
Block a user