fix view counting
This commit is contained in:
parent
acd8778864
commit
96e978aa2f
14
src/lib.rs
14
src/lib.rs
|
@ -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;
|
||||
|
||||
|
|
Loading…
Reference in a new issue