webframework_core/
form.rs1use crate::request::{FromRequest, Request};
2use crate::WebResult;
3
4use serde::de::DeserializeOwned;
5use failure::{Fail, Context, ResultExt};
6
7#[derive(Clone, Eq, PartialEq, Debug, Fail)]
8pub enum FormErrorKind {
9 #[fail(display = "An error occured during deserialization")]
10 DeserializationError,
11 #[fail(display = "The Content-Type could not be determined")]
12 UnknownContentTypeError,
13}
14
15#[derive(Debug)]
16pub struct FormError {
17 inner: Context<FormErrorKind>,
18}
19
20impl_fail_boilerplate!(FormErrorKind, FormError);
21
22
23#[derive(Debug, Clone)]
24pub struct Form<'a, T> {
25 req: &'a Request,
26 typ: std::marker::PhantomData<T>,
27}
28
29impl<'a, T: DeserializeOwned> Form<'a, T> {
30 pub fn get<S: AsRef<str>>(&self, _path: S) -> WebResult<T> {
31
32 let content_type = self.req.headers().get(http::header::CONTENT_TYPE)
33 .ok_or(FormErrorKind::UnknownContentTypeError.into())
34 .and_then(|val| val.to_str().context(FormErrorKind::UnknownContentTypeError))?;
35
36 match content_type {
37 "application/x-www-form-urlencoded" => {
38 Ok(serde_urlencoded::from_bytes(
39 self.req.body()).context(FormErrorKind::DeserializationError
40 )?)
41 }
42
43 _ => {
44 Err(FormErrorKind::UnknownContentTypeError)?
45 }
46 }
47 }
48}
49
50impl<'a, T: DeserializeOwned> FromRequest<'a> for Form<'a, T> {
51 fn from_request(req: &'a Request) -> WebResult<Form<'a, T>> {
52 Ok(Form { req, typ: std::marker::PhantomData })
53 }
54}