use super::{Headers, Method, Version};
#[derive(Debug, Clone)]
pub struct Request {
method: Method,
target: String,
version: Version,
headers: Headers,
body: Vec<u8>,
#[cfg(feature = "router")]
params: Vec<(String, String)>,
}
impl Request {
pub(crate) fn new(
method: Method,
target: String,
version: Version,
headers: Headers,
body: Vec<u8>,
) -> Request {
Request {
method,
target,
version,
headers,
body,
#[cfg(feature = "router")]
params: Vec::new(),
}
}
pub fn method(&self) -> &Method {
&self.method
}
pub fn target(&self) -> &str {
&self.target
}
pub fn path(&self) -> &str {
match self.target.split_once('?') {
Some((path, _)) => path,
None => &self.target,
}
}
pub fn query(&self) -> Option<&str> {
self.target.split_once('?').map(|(_, q)| q)
}
pub fn version(&self) -> Version {
self.version
}
pub fn headers(&self) -> &Headers {
&self.headers
}
pub fn host(&self) -> Option<&str> {
self.headers.get("host")
}
pub fn body(&self) -> &[u8] {
&self.body
}
pub fn body_str(&self) -> std::borrow::Cow<'_, str> {
String::from_utf8_lossy(&self.body)
}
pub fn into_body(self) -> Vec<u8> {
self.body
}
#[cfg(feature = "router")]
pub fn param(&self, name: &str) -> Option<&str> {
self.params
.iter()
.find(|(k, _)| k == name)
.map(|(_, v)| v.as_str())
}
#[cfg(feature = "router")]
pub fn params(&self) -> impl Iterator<Item = (&str, &str)> {
self.params.iter().map(|(k, v)| (k.as_str(), v.as_str()))
}
#[cfg(feature = "router")]
pub(crate) fn set_params(&mut self, params: Vec<(String, String)>) {
self.params = params;
}
}