use actix_web::HttpRequest;
fn strip_port(host: &str) -> &str {
host.split(":").collect::<Vec<&str>>()[0]
}
pub fn extract_host(req: &HttpRequest) -> Option<String> {
let req_host = req.uri().host();
let authority = req.uri().clone().into_parts().authority;
let header_host = req.headers().get("host");
if req_host.is_some() {
let host = req_host.unwrap().to_string();
return Some(strip_port(&host).to_string());
}
if authority.is_some() {
let authority = authority.unwrap().to_string();
let host = authority.split(":").collect::<Vec<&str>>()[0];
let host = strip_port(&host);
return Some(host.to_string());
}
if header_host.is_some() {
let host = header_host.unwrap().to_str().unwrap().to_string();
return Some(strip_port(&host).to_string());
}
None
}
pub fn extract_port(req: &HttpRequest) -> Option<u16> {
let req_host = req.uri().host();
let authority = req.uri().clone().into_parts().authority;
let header_host = req.headers().get("host");
if req_host.is_some() {
let host = req_host.unwrap().to_string();
let port = host.split(":").collect::<Vec<&str>>()[1];
return Some(port.parse::<u16>().unwrap());
}
if authority.is_some() {
let authority = authority.unwrap().to_string();
let port = authority.split(":").collect::<Vec<&str>>()[1];
return Some(port.parse::<u16>().unwrap());
}
if header_host.is_some() {
let host = header_host.unwrap().to_str().unwrap().to_string();
let port = host.split(":").collect::<Vec<&str>>()[1];
return Some(port.parse::<u16>().unwrap());
}
None
}
pub fn extract_real_ip(req: &HttpRequest) -> Option<String> {
let header_precedence: [&str; 4] = [
"cf-connecting-ip",
"x-real-ip",
"x-forwarded-for",
"x-client-ip"
];
for header in header_precedence.iter() {
let ip = req.headers().get(header.to_string());
if ip.is_some() {
return Some(ip.unwrap().to_str().unwrap().to_string());
}
}
let ip = req.peer_addr();
if ip.is_none() {
return None;
}
let ip = ip.unwrap().ip().to_string();
Some(ip)
}