aboutsummaryrefslogtreecommitdiff
path: root/src/request.rs
diff options
context:
space:
mode:
Diffstat (limited to 'src/request.rs')
-rw-r--r--src/request.rs74
1 files changed, 53 insertions, 21 deletions
diff --git a/src/request.rs b/src/request.rs
index 19292a1..6b8dbe1 100644
--- a/src/request.rs
+++ b/src/request.rs
@@ -5,13 +5,13 @@ use serde::Deserialize;
use std::str::Split;
use std::time::Duration;
-use crate::response::{Cookie, SputnikHeaders, delete_cookie};
-use crate::http::{HeaderMap, header, request::Parts};
+use crate::http::{header, request::Parts, HeaderMap};
+use crate::response::{delete_cookie, Cookie, SputnikHeaders};
/// Adds convenience methods to [`http::request::Parts`](Parts).
pub trait SputnikParts {
/// Parses the query string of the request into a given struct.
- fn query<'a, X: Deserialize<'a>>(&'a self) -> Result<X,QueryError>;
+ fn query<'a, X: Deserialize<'a>>(&'a self) -> Result<X, QueryError>;
/// Parses the cookies of the request.
fn cookies(&self) -> CookieIter;
@@ -42,7 +42,7 @@ impl<'a> Iterator for CookieIter<'a> {
None => self.next(),
Some(mut value) => {
if value.starts_with('"') && value.ends_with('"') && value.len() >= 2 {
- value = &value[1..value.len()-1];
+ value = &value[1..value.len() - 1];
}
Some((name, value))
}
@@ -52,7 +52,7 @@ impl<'a> Iterator for CookieIter<'a> {
}
impl SputnikParts for Parts {
- fn query<'a, T: Deserialize<'a>>(&'a self) -> Result<T,QueryError> {
+ fn query<'a, T: Deserialize<'a>>(&'a self) -> Result<T, QueryError> {
serde_urlencoded::from_str::<T>(self.uri.query().unwrap_or("")).map_err(QueryError)
}
@@ -64,16 +64,29 @@ impl SputnikParts for Parts {
}
fn cookies(&self) -> CookieIter {
- CookieIter(self.headers.get(header::COOKIE).and_then(|h| std::str::from_utf8(h.as_bytes()).ok()).unwrap_or("").split(';'))
+ CookieIter(
+ self.headers
+ .get(header::COOKIE)
+ .and_then(|h| std::str::from_utf8(h.as_bytes()).ok())
+ .unwrap_or("")
+ .split(';'),
+ )
}
fn enforce_content_type(&self, mime: Mime) -> Result<(), WrongContentTypeError> {
if let Some(content_type) = self.headers.get(header::CONTENT_TYPE) {
if *content_type == mime.to_string() {
- return Ok(())
+ return Ok(());
}
}
- Err(WrongContentTypeError{expected: mime, received: self.headers.get(header::CONTENT_TYPE).as_ref().and_then(|h| h.to_str().ok().map(|s| s.to_owned()))})
+ Err(WrongContentTypeError {
+ expected: mime,
+ received: self
+ .headers
+ .get(header::CONTENT_TYPE)
+ .as_ref()
+ .and_then(|h| h.to_str().ok().map(|s| s.to_owned())),
+ })
}
}
@@ -100,33 +113,50 @@ impl Flash {
/// If the request has a flash cookie retrieve it and append a set-cookie
/// header to delete the cookie to [`SputnikParts::response_headers`].
pub fn from_request(req: &mut Parts) -> Option<Self> {
- let value = req.cookies().find(|(name, _value)| *name == FLASH_COOKIE_NAME)?.1.to_owned();
- req.response_headers().set_cookie(delete_cookie(FLASH_COOKIE_NAME));
+ let value = req
+ .cookies()
+ .find(|(name, _value)| *name == FLASH_COOKIE_NAME)?
+ .1
+ .to_owned();
+ req.response_headers()
+ .set_cookie(delete_cookie(FLASH_COOKIE_NAME));
let mut iter = value.splitn(2, ':');
if let (Some(name), Some(message)) = (iter.next(), iter.next()) {
- return Some(Flash{name: name.to_owned(), message: message.to_owned()})
+ return Some(Flash {
+ name: name.to_owned(),
+ message: message.to_owned(),
+ });
}
None
}
/// Constructs a new Flash message. The name must not contain a colon (`:`).
pub fn new(name: String, message: String) -> Self {
- Flash{name, message}
+ Flash { name, message }
}
/// Constructs a new "success" Flash message.
pub fn success(message: String) -> Self {
- Flash{name: "success".to_owned(), message}
+ Flash {
+ name: "success".to_owned(),
+ message,
+ }
}
/// Constructs a new "warning" Flash message.
pub fn warning(message: String) -> Self {
- Flash{name: "warning".to_owned(), message}
+ Flash {
+ name: "warning".to_owned(),
+ message,
+ }
}
/// Constructs a new "error" Flash message.
pub fn error(message: String) -> Self {
- Flash{name: "error".to_owned(), message}
+ Flash {
+ name: "error".to_owned(),
+ message,
+ }
}
/// Returns the name of the Flash message.
@@ -140,7 +170,6 @@ impl Flash {
}
}
-
#[derive(thiserror::Error, Debug)]
#[error("query deserialize error: {0}")]
pub struct QueryError(pub serde_urlencoded::de::Error);
@@ -152,12 +181,11 @@ pub struct WrongContentTypeError {
pub received: Option<String>,
}
-
#[cfg(test)]
mod tests {
use std::convert::TryInto;
- use crate::http::{Request, header};
+ use crate::http::{header, Request};
use super::SputnikParts;
@@ -166,10 +194,14 @@ mod tests {
let (mut parts, _body) = Request::new("").into_parts();
assert!(parts.enforce_content_type(mime::APPLICATION_JSON).is_err());
- parts.headers.append(header::CONTENT_TYPE, "application/json".try_into().unwrap());
+ parts
+ .headers
+ .append(header::CONTENT_TYPE, "application/json".try_into().unwrap());
assert!(parts.enforce_content_type(mime::APPLICATION_JSON).is_ok());
- parts.headers.insert(header::CONTENT_TYPE, "text/html".try_into().unwrap());
+ parts
+ .headers
+ .insert(header::CONTENT_TYPE, "text/html".try_into().unwrap());
assert!(parts.enforce_content_type(mime::APPLICATION_JSON).is_err());
}
-} \ No newline at end of file
+}