Handle POST requests
This commit is contained in:
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)
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user