use crate::data_map::SharedDataMap;
use crate::types::{RequestMeta, RouteParams};
use hyper::Request;
use std::net::SocketAddr;
pub trait RequestExt {
fn params(&self) -> &RouteParams;
fn param<P: Into<String>>(&self, param_name: P) -> Option<&String>;
fn remote_addr(&self) -> SocketAddr;
fn data<T: Send + Sync + 'static>(&self) -> Option<&T>;
}
impl RequestExt for Request<hyper::Body> {
fn params(&self) -> &RouteParams {
self.extensions()
.get::<RequestMeta>()
.and_then(|meta| meta.route_params())
.expect("Routerify: No RouteParams added while processing request")
}
fn param<P: Into<String>>(&self, param_name: P) -> Option<&String> {
self.params().get(¶m_name.into())
}
fn remote_addr(&self) -> SocketAddr {
self.extensions()
.get::<RequestMeta>()
.and_then(|meta| meta.remote_addr())
.copied()
.expect("Routerify: No remote address added while processing request")
}
fn data<T: Send + Sync + 'static>(&self) -> Option<&T> {
let shared_data_maps = self.extensions().get::<Vec<SharedDataMap>>();
if let Some(shared_data_maps) = shared_data_maps {
for shared_data_map in shared_data_maps.iter() {
if let Some(data) = shared_data_map.inner.get::<T>() {
return Some(data);
}
}
}
return None;
}
}