use std::{future::Future, pin::Pin};
use actix_web::HttpRequest;
use crate::models::{app::MiddlewareNext, response::Response};
use colored::Colorize;
pub fn logger(req: &HttpRequest) -> Pin<Box<dyn Future<Output = Result<Response, MiddlewareNext>>>> {
let req_clone = req.clone();
Box::pin(async move {
let ip = req_clone.peer_addr();
let mut ip_str = "";
let mut actual_ip = String::new();
if ip.is_none() {
let real_ip = req_clone.headers().get("x-real-ip");
if real_ip.is_some() {
ip_str = real_ip.unwrap().to_str().unwrap();
} else {
let x_forwarded_for = req_clone.headers().get("x-forwarded-for");
if x_forwarded_for.is_some() {
ip_str = x_forwarded_for.unwrap().to_str().unwrap();
} else {
ip_str = "unknown";
}
}
} else {
actual_ip = ip.unwrap().ip().to_string();
}
if actual_ip.is_empty() {
actual_ip = ip_str.to_string();
}
println!("[{}] {} -> {}: {}", "LOGGER".bright_green(), actual_ip.as_str().blue(), req_clone.method().to_string().green(), req_clone.uri().path().yellow());
println!(" -> {}", req_clone.headers().get("user-agent").unwrap().to_str().unwrap().magenta());
Err(MiddlewareNext::Next)
})
}