feat: add route handlers, router, SSR template, and CSS

This commit is contained in:
NetworkCats
2026-03-02 20:02:45 +08:00
parent 7b2adffb46
commit 9f3b38acac
5 changed files with 424 additions and 0 deletions
+240
View File
@@ -0,0 +1,240 @@
use std::net::IpAddr;
use askama::Template;
use axum::extract::{Query, State};
use axum::http::{HeaderMap, StatusCode};
use axum::response::{Html, IntoResponse, Response};
use crate::cli_detect::is_cli_user_agent;
use crate::db::{self, SharedDb};
use crate::error::AppError;
use crate::models::{IpInfo, get_en_name};
#[derive(serde::Deserialize)]
pub struct IpQuery {
pub ip: Option<String>,
}
#[derive(Clone)]
pub struct AppState {
pub db: SharedDb,
pub site_domain: String,
}
#[derive(Template)]
#[template(path = "index.html")]
struct IndexTemplate {
ip: String,
query: String,
site_domain: String,
asn: String,
org: String,
country: String,
city: String,
is_proxy: bool,
is_vpn: bool,
is_hosting: bool,
is_tor: bool,
}
fn resolve_ip(headers: &HeaderMap, query: &IpQuery) -> Result<IpAddr, AppError> {
if let Some(ref ip_str) = query.ip {
let trimmed = ip_str.trim();
if !trimmed.is_empty() {
return trimmed.parse().map_err(|_| AppError::InvalidIp);
}
}
extract_client_ip(headers)
}
fn extract_client_ip(headers: &HeaderMap) -> Result<IpAddr, AppError> {
headers
.get("CF-Connecting-IP")
.and_then(|v| v.to_str().ok())
.and_then(|s| s.trim().parse().ok())
.ok_or(AppError::IpNotFound)
}
fn lookup_ip(db: &SharedDb, ip: IpAddr) -> Result<IpInfo, AppError> {
let reader = db.load();
db::lookup(&reader, ip).ok_or(AppError::DbLookupFailed)
}
fn wants_json(headers: &HeaderMap) -> bool {
headers
.get("Accept")
.and_then(|v| v.to_str().ok())
.is_some_and(|v| v.contains("application/json"))
}
fn format_asn(info: &IpInfo) -> String {
info.asn
.as_ref()
.and_then(|a| a.autonomous_system_number)
.map(|n| format!("AS{n}"))
.unwrap_or_default()
}
fn format_org(info: &IpInfo) -> String {
info.asn
.as_ref()
.and_then(|a| a.autonomous_system_organization.clone())
.unwrap_or_default()
}
fn format_country(info: &IpInfo) -> String {
info.country
.as_ref()
.map(|c| get_en_name(&c.names))
.unwrap_or_default()
}
fn format_city(info: &IpInfo) -> String {
info.city
.as_ref()
.map(|c| get_en_name(&c.names))
.unwrap_or_default()
}
pub async fn root(
State(state): State<AppState>,
headers: HeaderMap,
Query(query): Query<IpQuery>,
) -> Result<Response, AppError> {
let ua = headers
.get("User-Agent")
.and_then(|v| v.to_str().ok())
.unwrap_or("");
if is_cli_user_agent(ua) && query.ip.is_none() {
let ip = extract_client_ip(&headers)?;
return Ok(format!("{ip}\n").into_response());
}
if wants_json(&headers) && query.ip.is_none() {
let ip = extract_client_ip(&headers)?;
let info = lookup_ip(&state.db, ip)?;
return Ok(axum::Json(info).into_response());
}
let ip = resolve_ip(&headers, &query)?;
let info = lookup_ip(&state.db, ip)?;
let template = IndexTemplate {
ip: info.ip.clone(),
query: query.ip.unwrap_or_default(),
site_domain: state.site_domain.clone(),
asn: format_asn(&info),
org: format_org(&info),
country: format_country(&info),
city: format_city(&info),
is_proxy: info.proxy.is_proxy,
is_vpn: info.proxy.is_vpn,
is_hosting: info.proxy.is_hosting,
is_tor: info.proxy.is_tor,
};
Ok(Html(template.render().map_err(|_| AppError::DbLookupFailed)?).into_response())
}
pub async fn health() -> StatusCode {
StatusCode::OK
}
pub async fn json_handler(
State(state): State<AppState>,
headers: HeaderMap,
Query(query): Query<IpQuery>,
) -> Result<axum::Json<IpInfo>, AppError> {
let ip = resolve_ip(&headers, &query)?;
let info = lookup_ip(&state.db, ip)?;
Ok(axum::Json(info))
}
pub async fn ip_handler(
headers: HeaderMap,
Query(query): Query<IpQuery>,
) -> Result<String, AppError> {
let ip = resolve_ip(&headers, &query)?;
Ok(format!("{ip}\n"))
}
pub async fn asn_handler(
State(state): State<AppState>,
headers: HeaderMap,
Query(query): Query<IpQuery>,
) -> Result<String, AppError> {
let ip = resolve_ip(&headers, &query)?;
let info = lookup_ip(&state.db, ip)?;
Ok(format!("{}\n", format_asn(&info)))
}
pub async fn org_handler(
State(state): State<AppState>,
headers: HeaderMap,
Query(query): Query<IpQuery>,
) -> Result<String, AppError> {
let ip = resolve_ip(&headers, &query)?;
let info = lookup_ip(&state.db, ip)?;
Ok(format!("{}\n", format_org(&info)))
}
pub async fn country_handler(
State(state): State<AppState>,
headers: HeaderMap,
Query(query): Query<IpQuery>,
) -> Result<String, AppError> {
let ip = resolve_ip(&headers, &query)?;
let info = lookup_ip(&state.db, ip)?;
Ok(format!("{}\n", format_country(&info)))
}
pub async fn city_handler(
State(state): State<AppState>,
headers: HeaderMap,
Query(query): Query<IpQuery>,
) -> Result<String, AppError> {
let ip = resolve_ip(&headers, &query)?;
let info = lookup_ip(&state.db, ip)?;
Ok(format!("{}\n", format_city(&info)))
}
pub async fn proxy_handler(
State(state): State<AppState>,
headers: HeaderMap,
Query(query): Query<IpQuery>,
) -> Result<String, AppError> {
let ip = resolve_ip(&headers, &query)?;
let info = lookup_ip(&state.db, ip)?;
Ok(format!("{}\n", info.proxy.is_proxy))
}
pub async fn vpn_handler(
State(state): State<AppState>,
headers: HeaderMap,
Query(query): Query<IpQuery>,
) -> Result<String, AppError> {
let ip = resolve_ip(&headers, &query)?;
let info = lookup_ip(&state.db, ip)?;
Ok(format!("{}\n", info.proxy.is_vpn))
}
pub async fn hosting_handler(
State(state): State<AppState>,
headers: HeaderMap,
Query(query): Query<IpQuery>,
) -> Result<String, AppError> {
let ip = resolve_ip(&headers, &query)?;
let info = lookup_ip(&state.db, ip)?;
Ok(format!("{}\n", info.proxy.is_hosting))
}
pub async fn tor_handler(
State(state): State<AppState>,
headers: HeaderMap,
Query(query): Query<IpQuery>,
) -> Result<String, AppError> {
let ip = resolve_ip(&headers, &query)?;
let info = lookup_ip(&state.db, ip)?;
Ok(format!("{}\n", info.proxy.is_tor))
}
+2
View File
@@ -2,7 +2,9 @@ mod cli_detect;
mod config;
mod db;
mod error;
mod handlers;
mod models;
mod routes;
mod updater;
fn main() {
+23
View File
@@ -0,0 +1,23 @@
use axum::routing::get;
use axum::Router;
use tower_http::services::ServeDir;
use crate::handlers::{self, AppState};
pub fn build_router(state: AppState) -> Router {
Router::new()
.route("/", get(handlers::root))
.route("/health", get(handlers::health))
.route("/json", get(handlers::json_handler))
.route("/ip", get(handlers::ip_handler))
.route("/asn", get(handlers::asn_handler))
.route("/org", get(handlers::org_handler))
.route("/country", get(handlers::country_handler))
.route("/city", get(handlers::city_handler))
.route("/proxy", get(handlers::proxy_handler))
.route("/vpn", get(handlers::vpn_handler))
.route("/hosting", get(handlers::hosting_handler))
.route("/tor", get(handlers::tor_handler))
.nest_service("/static", ServeDir::new("static"))
.with_state(state)
}
+96
View File
@@ -0,0 +1,96 @@
*,
*::before,
*::after {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: "Inter", "Segoe UI", system-ui, -apple-system, sans-serif;
color: #1a1a1a;
background: #fff;
-webkit-font-smoothing: antialiased;
}
main {
max-width: 540px;
margin: 80px auto 0;
padding: 0 20px;
}
.search-form {
display: flex;
gap: 8px;
}
.search-form input {
flex: 1;
height: 38px;
padding: 0 12px;
border: 1px solid #d0d0d0;
border-radius: 6px;
font-size: 14px;
font-family: inherit;
color: #1a1a1a;
background: #fff;
outline: none;
}
.search-form input:focus {
border-color: #999;
}
.search-form input::placeholder {
color: #999;
}
.search-form button {
height: 38px;
padding: 0 16px;
border: 1px solid #d0d0d0;
border-radius: 6px;
font-size: 14px;
font-family: inherit;
color: #1a1a1a;
background: #fafafa;
cursor: pointer;
}
.search-form button:hover {
background: #f0f0f0;
}
.ip-display {
text-align: center;
font-size: 42px;
font-weight: 600;
margin: 40px 0 32px;
letter-spacing: -0.5px;
}
.info-table {
width: 100%;
border-collapse: collapse;
}
.info-table td {
padding: 10px 4px;
border-top: 1px solid #eee;
font-size: 15px;
vertical-align: top;
}
.info-table tr:last-child td {
border-bottom: 1px solid #eee;
}
.info-table .label {
width: 120px;
font-weight: 600;
color: #1a1a1a;
}
.info-table .bool-true {
color: #16a34a;
}
+63
View File
@@ -0,0 +1,63 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>{{ ip }} - {{ site_domain }}</title>
<link rel="stylesheet" href="/static/style.css">
</head>
<body>
<main>
<form method="GET" action="/" class="search-form">
<input
type="text"
name="ip"
placeholder="Type to search IP data"
value="{{ query }}"
autocomplete="off"
spellcheck="false"
>
<button type="submit">Lookup</button>
</form>
<h1 class="ip-display">{{ ip }}</h1>
<table class="info-table">
<tbody>
<tr>
<td class="label">ASN</td>
<td>{{ asn }}</td>
</tr>
<tr>
<td class="label">Org</td>
<td>{{ org }}</td>
</tr>
<tr>
<td class="label">Country</td>
<td>{{ country }}</td>
</tr>
<tr>
<td class="label">City</td>
<td>{{ city }}</td>
</tr>
<tr>
<td class="label">Proxy</td>
<td{% if is_proxy %} class="bool-true"{% endif %}>{{ is_proxy }}</td>
</tr>
<tr>
<td class="label">VPN</td>
<td{% if is_vpn %} class="bool-true"{% endif %}>{{ is_vpn }}</td>
</tr>
<tr>
<td class="label">Hosting</td>
<td{% if is_hosting %} class="bool-true"{% endif %}>{{ is_hosting }}</td>
</tr>
<tr>
<td class="label">Tor</td>
<td{% if is_tor %} class="bool-true"{% endif %}>{{ is_tor }}</td>
</tr>
</tbody>
</table>
</main>
</body>
</html>