use std::convert::Infallible; use hyper::service::{service_fn, make_service_fn}; use hyper::{Method, Server, StatusCode}; use serde::Deserialize; use sputnik::security::CsrfToken; use sputnik::{request::{Parts, Body}, response::Response}; use sputnik::request::error::*; #[derive(thiserror::Error, Debug)] enum Error { #[error("page not found")] NotFound(String), #[error("{0}")] CsrfError(#[from] CsrfProtectedFormError) } fn render_error(err: Error) -> (StatusCode, String) { match err { Error::NotFound(msg) => (StatusCode::NOT_FOUND, msg), Error::CsrfError(err) => (StatusCode::BAD_REQUEST, err.to_string()), } } async fn route(req: &mut Parts, body: Body) -> Result { match (req.method(), req.uri().path()) { (&Method::GET, "/form") => get_form(req).await, (&Method::POST, "/form") => post_form(req, body).await, _ => return Err(Error::NotFound("page not found".to_owned())) } } async fn get_form(req: &mut Parts) -> Result { let mut response = Response::new(); let csrf_token = CsrfToken::from_parts(req, &mut response); *response.body() = format!("
{}
", csrf_token.html_input()).into(); Ok(response) } #[derive(Deserialize)] struct FormData {text: String} async fn post_form(req: &mut Parts, body: Body) -> Result { let mut response = Response::new(); let csrf_token = CsrfToken::from_parts(req, &mut response); let msg: FormData = body.into_form_csrf(&csrf_token).await?; *response.body() = format!("hello {}", msg.text).into(); Ok(response) } /// adapt between Hyper's types and Sputnik's convenience types async fn service(req: hyper::Request) -> Result, Infallible> { let (mut parts, body) = sputnik::request::adapt(req); match route(&mut parts, body).await { Ok(res) => Ok(res.into()), Err(err) => { let (code, message) = render_error(err); // you can easily wrap or log errors here Ok(hyper::Response::builder().status(code).body(message.into()).unwrap()) } } } #[tokio::main] async fn main() { let service = make_service_fn(move |_| { async move { Ok::<_, hyper::Error>(service_fn(move |req| { service(req) })) } }); let addr = ([127, 0, 0, 1], 8000).into(); let server = Server::bind(&addr).serve(service); println!("Listening on http://{}", addr); server.await; }