#[cfg(feature = "multipart")]
use crate::multipart::FilePart;
use crate::{
body::HttpBody,
error::Error,
extract::Extract,
multipart::FormData,
serde_request::{
from_str_map, from_str_multi_map, from_str_multi_val, from_str_val, RequestDeserializer,
},
};
#[cfg(feature = "cookie")]
use cookie::{Cookie, CookieJar};
use headers::{Header, HeaderMapExt};
use http_body_util::{BodyExt, Limited};
use hyper::{body::Bytes, header::AsHeaderName};
use multimap::MultiMap;
use once_cell::sync::OnceCell;
use serde::{de::DeserializeOwned, Deserialize};
use std::{
any::Any,
collections::HashMap,
net::SocketAddr,
ops::{Deref, DerefMut},
sync::{Arc, RwLock},
};
pub struct Request {
inner: hyper::http::Request<HttpBody>,
params: HashMap<String, String>,
queries: OnceCell<MultiMap<String, String>>,
pub(crate) form_data: tokio::sync::OnceCell<FormData>,
pub(crate) payload: tokio::sync::OnceCell<Bytes>,
#[cfg(feature = "cookie")]
cookies: CookieJar,
depot: Arc<RwLock<HashMap<String, Box<dyn AnyClone + Send + Sync>>>>,
}
impl Request {
#[inline]
pub(crate) fn new(
inner: hyper::http::Request<HttpBody>,
depot: Arc<RwLock<HashMap<String, Box<dyn AnyClone + Send + Sync>>>>,
) -> Self {
#[cfg(feature = "cookie")]
let cookies = if let Some(cookie_iter) = inner
.headers()
.get("Cookie")
.and_then(|cookies| cookies.to_str().ok())
.map(|cookies_str| cookies_str.split(';').map(|s| s.trim()))
.map(|cookie_iter| {
cookie_iter.filter_map(|cookie_s| Cookie::parse_encoded(cookie_s.to_string()).ok())
}) {
let mut jar = CookieJar::new();
cookie_iter.for_each(|c| jar.add_original(c));
jar
} else {
CookieJar::new()
};
Request {
inner,
params: HashMap::new(),
queries: OnceCell::new(),
form_data: tokio::sync::OnceCell::new(),
payload: tokio::sync::OnceCell::new(),
#[cfg(feature = "cookie")]
cookies,
depot,
}
}
#[inline]
pub fn request(&mut self) -> &mut hyper::Request<HttpBody> {
&mut self.inner
}
#[cfg(feature = "cookie")]
#[inline]
pub fn cookie(&self, name: &str) -> Option<&Cookie<'static>> {
self.cookies.get(name)
}
#[cfg(feature = "cookie")]
#[inline]
pub fn cookies(&self) -> &CookieJar {
&self.cookies
}
#[cfg(feature = "cookie")]
#[inline]
pub fn cookies_mut(&mut self) -> &mut CookieJar {
&mut self.cookies
}
#[cfg(feature = "cookie")]
#[inline]
pub fn parse_cookies<'de, T>(&'de self) -> Result<T,Error>
where
T: Deserialize<'de>,
{
let iter = self.cookies.iter().map(|c| c.name_value());
from_str_map(iter).map_err(Error::Deserialize)
}
#[inline]
pub fn accept(&self) -> Vec<mime::Mime> {
let mut list: Vec<mime::Mime> = vec![];
if let Some(accept) = self
.inner
.headers()
.get("accept")
.and_then(|h| h.to_str().ok())
{
let parts: Vec<&str> = accept.split(',').collect();
for part in parts {
if let Ok(mt) = part.parse() {
list.push(mt);
}
}
}
list
}
#[inline]
pub fn first_accept(&self) -> Option<mime::Mime> {
let mut accept = self.accept();
if !accept.is_empty() {
Some(accept.remove(0))
} else {
None
}
}
#[inline]
pub fn header_typed_get<T: Header>(&self) -> Option<T> {
self.inner.headers().typed_get()
}
#[inline]
pub fn header<'de, T>(&'de self, key: impl AsHeaderName) -> Option<T>
where
T: Deserialize<'de>,
{
let values = self
.inner
.headers()
.get_all(key)
.iter()
.filter_map(|v| v.to_str().ok())
.collect::<Vec<_>>();
from_str_multi_val(values).ok()
}
#[inline]
pub fn parse_header<'de, T>(&'de self) -> Result<T,Error>
where
T: Deserialize<'de>,
{
let iter = self
.inner
.headers()
.iter()
.map(|(k, v)| (k.as_str(), v.to_str().unwrap_or_default()));
from_str_map(iter).map_err(Error::Deserialize)
}
#[inline]
pub fn remote_addr(&self) -> SocketAddr {
**self.extensions().get::<Arc<SocketAddr>>().unwrap()
}
#[inline]
pub fn params(&self) -> &HashMap<String, String> {
&self.params
}
#[inline]
pub fn params_mut(&mut self) -> &mut HashMap<String, String> {
&mut self.params
}
#[inline]
pub fn param<'de, T>(&'de self, key: &str) -> Option<T>
where
T: serde::Deserialize<'de>,
{
self.params.get(key).and_then(|v| from_str_val(v).ok())
}
#[inline]
pub fn parse_param<'de, T>(&'de self) -> Result<T,Error>
where
T: serde::Deserialize<'de>,
{
let params = self.params.iter();
from_str_map(params).map_err(Error::Deserialize)
}
#[inline]
pub fn queries(&self) -> &MultiMap<String, String> {
self.queries.get_or_init(|| {
form_urlencoded::parse(self.inner.uri().query().unwrap_or("").as_bytes())
.into_owned()
.collect()
})
}
#[inline]
pub fn query<'de, T>(&'de self, key: &str) -> Option<T>
where
T: serde::Deserialize<'de>,
{
self.queries()
.get_vec(key)
.and_then(|vs| from_str_multi_val(vs).ok())
}
#[inline]
pub fn parse_query<'de, T>(&'de self) -> Result<T,Error>
where
T: serde::Deserialize<'de>,
{
let queries = self.queries().iter_all();
from_str_multi_map(queries).map_err(Error::Deserialize)
}
#[inline]
pub fn content_type(&self) -> Option<mime::Mime> {
self.inner
.headers()
.get("content-type")
.and_then(|h| h.to_str().ok())
.and_then(|v| v.parse().ok())
}
#[inline]
pub fn content_type_str(&self) -> Option<&str> {
self.inner
.headers()
.get("content-type")
.and_then(|h| h.to_str().ok())
}
#[inline]
pub async fn payload(&mut self) -> Result<&Bytes,Error> {
let body = std::mem::replace(self.body_mut(), HttpBody::Empty);
self.payload
.get_or_try_init(|| async {
Ok(Limited::new(body, 64 * 1024)
.collect()
.await
.map_err(Error::Boxed)?
.to_bytes())
})
.await
}
#[inline]
pub async fn form_data(&mut self) -> Result<&FormData,Error> {
let body = std::mem::replace(self.body_mut(), HttpBody::Empty);
let ctype = self.content_type_str();
self.form_data
.get_or_try_init(|| async { FormData::new(ctype, body).await })
.await
}
#[inline]
pub async fn form<'de, T>(&'de mut self, key: &str) -> Option<T>
where
T: serde::Deserialize<'de>,
{
self.form_data()
.await
.ok()
.and_then(|ps| ps.fields.get_vec(key))
.and_then(|vs| from_str_multi_val(vs).ok())
}
#[cfg(feature = "multipart")]
#[inline]
pub async fn file<'a>(&'a mut self, key: &'a str) -> Option<&'a FilePart> {
self.form_data().await.ok().and_then(|ps| ps.files.get(key))
}
#[cfg(feature = "multipart")]
#[inline]
pub async fn files<'a>(&'a mut self, key: &'a str) -> Option<&'a Vec<FilePart>> {
self.form_data()
.await
.ok()
.and_then(|ps| ps.files.get_vec(key))
}
#[cfg(feature = "multipart")]
#[inline]
pub async fn upload(&mut self, key: &str, save_path: &str) -> Result<u64,Error> {
if let Some(file) = self.file(key).await {
std::fs::create_dir_all(save_path)?;
let dest = format!("{}/{}", save_path, file.name().unwrap());
Ok(std::fs::copy(file.path(), std::path::Path::new(&dest))?)
} else {
Err(Error::Other(String::from(
"File not resolved from current request",
)))
}
}
#[cfg(feature = "multipart")]
#[inline]
pub async fn uploads(&mut self, key: &str, save_path: &str) -> Result<String,Error> {
if let Some(files) = self.files(key).await {
std::fs::create_dir_all(save_path)?;
let mut msgs = Vec::with_capacity(files.len());
for file in files {
let dest = format!("{}/{}", save_path, file.name().unwrap());
if let Err(e) = std::fs::copy(file.path(), std::path::Path::new(&dest)) {
return Ok(format!("file not found in request: {e}"));
} else {
msgs.push(dest);
}
}
Ok(format!("Files uploaded:\n\n{}", msgs.join("\n")))
} else {
Err(Error::Other(String::from(
"Files not resolved from current request",
)))
}
}
#[inline]
async fn inner_parse_json<'de, T>(&'de mut self) -> Result<T,Error>
where
T: Deserialize<'de>,
{
self.payload()
.await
.and_then(|payload| serde_json::from_slice::<T>(payload).map_err(Error::SerdeJson))
}
#[inline]
pub async fn parse_json<'de, T>(&'de mut self) -> Result<T,Error>
where
T: Deserialize<'de>,
{
let ctype = self.content_type();
if let Some(ctype) = ctype {
if ctype.subtype() == mime::JSON {
return self.inner_parse_json().await;
}
}
Err(Error::Other(String::from("Invalid request Context-Type")))
}
#[inline]
async fn inner_parse_form<'de, T>(&'de mut self) -> Result<T,Error>
where
T: Deserialize<'de>,
{
from_str_multi_map(self.form_data().await?.fields.iter_all()).map_err(Error::Deserialize)
}
#[inline]
pub async fn parse_form<'de, T>(&'de mut self) -> Result<T,Error>
where
T: Deserialize<'de>,
{
if let Some(ctype) = self.content_type() {
if ctype.subtype() == mime::WWW_FORM_URLENCODED || ctype.subtype() == mime::FORM_DATA {
return self.inner_parse_form().await;
}
}
Err(Error::Other(String::from("Invalid request Context-Type")))
}
#[inline]
pub async fn parse_body<T>(&mut self) -> Result<T,Error>
where
T: DeserializeOwned,
{
let ctype = self.content_type_str();
match ctype {
Some(ctype) if ctype == "application/json" => self.inner_parse_json().await,
Some(ctype)
if ctype == "application/x-www-form-urlencoded"
|| ctype.starts_with("multipart/form-data") =>
{
self.inner_parse_form().await
}
#[cfg(feature = "cbor")]
Some(ctype) if ctype == "application/cbor" => {
self.payload().await.and_then(|payload| {
ciborium::de::from_reader(&payload[..]).map_err(|e| Error::Other(e.to_string()))
})
}
#[cfg(feature = "msgpack")]
Some(ctype) if ctype == "application/msgpack" => self
.payload()
.await
.and_then(|payload| rmp_serde::from_slice(&payload).map_err(Error::MsgpackDe)),
_ => Err(Error::Other(String::from("Invalid request Context-Type"))),
}
}
#[inline]
pub async fn extract<'de, T>(&'de mut self) -> Result<T,Error>
where
T: Extract<'de> + Send,
{
Ok(T::deserialize(
RequestDeserializer::new(self, T::metadata()).await?,
)?)
}
#[inline]
pub fn insert<V>(&mut self, key: &str, value: V)
where
V: AnyClone + Send + Sync,
{
let mut data = self.depot.write().unwrap();
data.insert(key.to_owned(), Box::new(value));
}
#[inline]
pub fn get<V: Send + Sync + 'static>(&self, key: &str) -> Result<V, Option<Box<dyn Any>>> {
let data = self.depot.read().unwrap();
match data.get(key) {
Some(boxed) => boxed
.clone()
.into_any()
.downcast::<V>()
.map(|b| *b)
.map_err(Some),
None => Err(None),
}
}
#[inline]
pub fn remove<V: Send + Sync + 'static>(&mut self, key: &str) -> Option<V> {
let mut data = self.depot.write().unwrap();
if let Some(boxed) = data.remove(key) {
boxed.into_any().downcast().ok().map(|boxed| *boxed)
} else {
None
}
}
}
impl Deref for Request {
type Target = hyper::Request<HttpBody>;
#[inline]
fn deref(&self) -> &Self::Target {
&self.inner
}
}
impl DerefMut for Request {
#[inline]
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.inner
}
}
pub trait AnyClone: Any {
fn clone_box(&self) -> Box<dyn AnyClone + Send + Sync>;
fn as_any(&self) -> &dyn Any;
fn as_any_mut(&mut self) -> &mut dyn Any;
fn into_any(self: Box<Self>) -> Box<dyn Any>;
}
impl<T: Clone + Send + Sync + 'static> AnyClone for T {
fn clone_box(&self) -> Box<dyn AnyClone + Send + Sync> {
Box::new(self.clone())
}
fn as_any(&self) -> &dyn Any {
self
}
fn as_any_mut(&mut self) -> &mut dyn Any {
self
}
fn into_any(self: Box<Self>) -> Box<dyn Any> {
self
}
}
impl Clone for Box<dyn AnyClone + Send + Sync> {
fn clone(&self) -> Self {
(**self).clone_box()
}
}