From 3d1dda650325260487630f3c7e268c7d1c29b0ef Mon Sep 17 00:00:00 2001 From: itsscb Date: Sun, 25 Aug 2024 20:20:40 +0200 Subject: [PATCH] fix: always log ip - even if unknown --- src/main.rs | 26 ++++++++++++++++++-------- 1 file changed, 18 insertions(+), 8 deletions(-) diff --git a/src/main.rs b/src/main.rs index 58bb257..20fdcdd 100644 --- a/src/main.rs +++ b/src/main.rs @@ -35,14 +35,24 @@ async fn word() -> String { } async fn log_ip(req: Request, next: Next) -> Response { - if let Some(addr) = req.extensions().get::() { - info!( - PATH = req.uri().path().to_string(), - IP = addr.ip().to_string() - ); - } else { - info!(PATH = req.uri().path().to_string()); - } + let ip = req + .extensions() + .get::() + .map(|addr| addr.ip().to_string()) + .or_else(|| { + req.headers() + .get("x-forwarded-for") + .and_then(|hv| hv.to_str().ok().map(String::from)) + }) + .or_else(|| { + req.headers() + .get("x-real-ip") + .and_then(|hv| hv.to_str().ok().map(String::from)) + }) + .unwrap_or_else(|| "Unknown".to_string()); + + info!(PATH = req.uri().path().to_string(), IP = ip); + next.run(req).await }