fix view counting

This commit is contained in:
lelgenio 2024-10-05 17:25:58 -03:00
parent acd8778864
commit 96e978aa2f

View file

@ -10,6 +10,7 @@ use anyhow::{Context, Result};
use askama::Template;
use axum::{
extract::{ConnectInfo, State},
http::HeaderMap,
routing::get,
Router,
};
@ -102,13 +103,22 @@ async fn write_count(new_count: u32) -> anyhow::Result<()> {
Ok(())
}
fn ip_from_headers(headers: &HeaderMap) -> Option<IpAddr> {
let value = headers.get("x-forwarded-for")?;
let ip_str = String::from_utf8_lossy(value.as_bytes());
ip_str.parse::<IpAddr>().ok()
}
#[axum::debug_handler]
pub async fn home(
State(state): State<AppState>,
headers: HeaderMap,
ConnectInfo(addr): ConnectInfo<SocketAddr>,
) -> HomeTemplate {
let ip = addr.ip();
tracing::info!(ip = ip.to_string());
let direct_ip = addr.ip();
let ip: IpAddr = ip_from_headers(&headers).unwrap_or(direct_ip);
let view_count = state.increment(ip).await;