Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
134 changes: 133 additions & 1 deletion Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

8 changes: 5 additions & 3 deletions Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "rust_rest_api"
version = "0.1.5"
version = "0.2.0"
edition = "2024"
license = "MIT"
authors = ["Habibi-Dev"]
Expand All @@ -15,13 +15,15 @@ axum = "0.8.4"
tokio = { version = "1.47.1", features = ["full"] }
serde_json = { version = "1.0.145", features = ["preserve_order"] }
dotenvy = "0.15.7"
http = "1.3.1"
serde = { version = "1.0.228", features = ["derive"] }
chrono = "0.4.42"
chrono-tz = "0.10.4"
sea-orm = { version = "1.1.16", features = ["sqlx-sqlite", "runtime-tokio-rustls"] }
once_cell = "1.21.3"
rust-embed = "8.7.2"
askama = { version = "0.14", features = ["full"] }
tower-http = { version = "0.6.6", features = ["fs"] }
http = "1.3.1"

[dependencies.migration]
path = "./migration"
path = "./migration"
1 change: 1 addition & 0 deletions src/assets/index-Bu-dXgft.css

Large diffs are not rendered by default.

168 changes: 168 additions & 0 deletions src/assets/index-DM3BAv3J.js

Large diffs are not rendered by default.

4 changes: 2 additions & 2 deletions src/services/health/mod.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
mod response;
pub(crate) mod response;

use crate::services::AppState;
use axum::Router;
Expand All @@ -7,7 +7,7 @@ use response::{fallback, health_check, init};

pub fn routers(state: AppState) -> Router {
Router::new()
.route("/", get(init))
.route("/info", get(init))
.route("/health", get(health_check))
.fallback(fallback)
.with_state(state)
Expand Down
21 changes: 11 additions & 10 deletions src/services/health/response.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ pub async fn health_check() -> api_response::Json<ApiResponse<serde_json::Value>
})))
}

async fn collect_endpoint_stats(state: &AppState) -> EndpointStats {
pub async fn collect_endpoint_stats(state: &AppState) -> EndpointStats {
let total = state.stats_cache.total_hits().await;

let (health, time, tehran, ip, country, country_full) = tokio::join!(
Expand Down Expand Up @@ -89,7 +89,8 @@ fn build_api_info(stats: EndpointStats) -> serde_json::Value {
"contact": {
"homepage": "habibi-dev.ir",
"email": "habibi.dev@gmail.com",
"telegram": "https://t.me/habibi_dev"
"telegram": "https://t.me/habibi_dev",
"github": "https://github.com/habibi-dev/rest-api.ir"
}
})
}
Expand Down Expand Up @@ -124,12 +125,12 @@ fn build_endpoints_list() -> serde_json::Value {
])
}

struct EndpointStats {
total: u64,
health: Option<u64>,
time: Option<u64>,
tehran: Option<u64>,
ip: Option<u64>,
country: Option<u64>,
country_full: Option<u64>,
pub struct EndpointStats {
pub total: u64,
pub health: Option<u64>,
pub time: Option<u64>,
pub tehran: Option<u64>,
pub ip: Option<u64>,
pub country: Option<u64>,
pub country_full: Option<u64>,
}
44 changes: 44 additions & 0 deletions src/services/index/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
use crate::utility::url;
use askama::Template;
use axum::response::{Html, IntoResponse, Response};
use std::env;
use axum::extract::State;
use crate::services::AppState;
use crate::services::health::response::EndpointStats;

#[derive(Template)]
#[template(path = "index.html")]
struct IndexTemplate {
title: String,
version: String,
url: String,
domain: String,
stats: EndpointStats ,
}

impl IntoResponse for IndexTemplate {
fn into_response(self) -> Response {
match self.render() {
Ok(html) => Html(html).into_response(),
Err(_) => (
http::StatusCode::INTERNAL_SERVER_ERROR,
"Failed to render template",
)
.into_response(),
}
}
}

pub async fn index_handler(State(state): State<AppState>) -> impl IntoResponse {
let domain = env::var("APP_FINAL_DOMAIN").unwrap_or(String::from("localhost"));
const VERSION: &str = env!("CARGO_PKG_VERSION");
let stats = crate::services::health::response::collect_endpoint_stats(&state).await;

IndexTemplate {
title: "rest-api".into(),
version: VERSION.into(),
url: url("/"),
stats,
domain,
}
}
1 change: 1 addition & 0 deletions src/services/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ mod ip;
pub mod jobs;
pub mod routes;
mod time;
mod index;

pub use cache::StatsCache;
use sea_orm::DatabaseConnection;
Expand Down
21 changes: 17 additions & 4 deletions src/services/routes.rs
Original file line number Diff line number Diff line change
@@ -1,31 +1,44 @@
use crate::middleware::visit_event;
use crate::services::index::index_handler;
use crate::services::{AppState, country, health, ip, time};
use axum::routing::{MethodRouter, get};
use axum::{Router, middleware};
use std::path::PathBuf;
use tower_http::services::fs::ServeDir;

pub struct Routes;
impl Routes {
pub fn routes(app_state: AppState) -> Router {
let assets_path = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("src/assets");

// routes that need state
let stateful_routes = Router::new()
.route("/", get(index_handler))
.with_state(app_state.clone());

// routes that don't need state or have their own state
let api = Router::new()
.nest("/time", Self::generate(time::routers_list()))
.nest("/ip", Self::generate(ip::routers_list()))
.nest("/country", Self::generate(country::routers_list()))
.route("/flags/{code}", get(country::flag::get_flag));

Router::new()
.merge(stateful_routes)
.merge(health::routers(app_state.clone()))
.nest_service("/assets", ServeDir::new(assets_path))
.nest("/api/v1", api)
.route_layer(middleware::from_fn_with_state(
app_state.clone(),
visit_event,
))
}

pub fn generate(routers_list: Vec<(&str, MethodRouter)>) -> Router {
let routers = routers_list;
let mut app = Router::new();
for router in routers {
app = app.route(router.0, router.1);
for (path, method_router) in routers_list {
app = app.route(path, method_router);
}
app
}
}
}
Loading
Loading