diff options
Diffstat (limited to 'examples/csrf')
-rw-r--r-- | examples/csrf/Cargo.toml | 3 | ||||
-rw-r--r-- | examples/csrf/src/main.rs | 32 |
2 files changed, 25 insertions, 10 deletions
diff --git a/examples/csrf/Cargo.toml b/examples/csrf/Cargo.toml index 1f0066b..b6768ed 100644 --- a/examples/csrf/Cargo.toml +++ b/examples/csrf/Cargo.toml @@ -11,4 +11,5 @@ publish = false hyper = "0.13" sputnik = {path = "../../"} serde = { version = "1.0", features = ["derive"] } -tokio = { version = "0.2", features = ["full"] }
\ No newline at end of file +tokio = { version = "0.2", features = ["full"] } +thiserror = "1.0"
\ No newline at end of file diff --git a/examples/csrf/src/main.rs b/examples/csrf/src/main.rs index 497bd66..915d063 100644 --- a/examples/csrf/src/main.rs +++ b/examples/csrf/src/main.rs @@ -1,15 +1,31 @@ use std::convert::Infallible; use hyper::service::{service_fn, make_service_fn}; -use hyper::{Method, Server}; +use hyper::{Method, Server, StatusCode}; use serde::Deserialize; use sputnik::security::CsrfToken; -use sputnik::{Error, request::{Parts, Body}, response::Response}; +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<Response,Error> { match (req.method(), req.uri().path()) { (&Method::GET, "/form") => get_form(req).await, (&Method::POST, "/form") => post_form(req, body).await, - _ => return Err(Error::not_found("page not found".to_owned())) + _ => return Err(Error::NotFound("page not found".to_owned())) } } @@ -37,12 +53,10 @@ async fn service(req: hyper::Request<hyper::Body>) -> Result<hyper::Response<hyp let (mut parts, body) = sputnik::request::adapt(req); match route(&mut parts, body).await { Ok(res) => Ok(res.into()), - Err(err) => match err { - Error::Simple(err) => { - Ok(err.response_builder().body(err.message.into()).unwrap()) - // you can easily wrap or log errors here - } - Error::Response(err) => Ok(err) + 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()) } } } |