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 askama::Template;
|
||||||
use axum::{
|
use axum::{
|
||||||
extract::{ConnectInfo, State},
|
extract::{ConnectInfo, State},
|
||||||
|
http::HeaderMap,
|
||||||
routing::get,
|
routing::get,
|
||||||
Router,
|
Router,
|
||||||
};
|
};
|
||||||
|
@ -102,13 +103,22 @@ async fn write_count(new_count: u32) -> anyhow::Result<()> {
|
||||||
Ok(())
|
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]
|
#[axum::debug_handler]
|
||||||
pub async fn home(
|
pub async fn home(
|
||||||
State(state): State<AppState>,
|
State(state): State<AppState>,
|
||||||
|
headers: HeaderMap,
|
||||||
ConnectInfo(addr): ConnectInfo<SocketAddr>,
|
ConnectInfo(addr): ConnectInfo<SocketAddr>,
|
||||||
) -> HomeTemplate {
|
) -> HomeTemplate {
|
||||||
let ip = addr.ip();
|
let direct_ip = addr.ip();
|
||||||
tracing::info!(ip = ip.to_string());
|
|
||||||
|
let ip: IpAddr = ip_from_headers(&headers).unwrap_or(direct_ip);
|
||||||
|
|
||||||
let view_count = state.increment(ip).await;
|
let view_count = state.increment(ip).await;
|
||||||
|
|
||||||
|
|
Loading…
Reference in a new issue