healthcheck endpoint
This commit is contained in:
parent
04b2b056cc
commit
2bf07e3e9b
1 changed files with 68 additions and 2 deletions
70
src/main.rs
70
src/main.rs
|
|
@ -1,3 +1,69 @@
|
|||
fn main() {
|
||||
println!("Hello, world!");
|
||||
// src/main.rs
|
||||
|
||||
use axum::{
|
||||
extract::State,
|
||||
http::StatusCode,
|
||||
response::{IntoResponse, Json},
|
||||
routing::get,
|
||||
Router,
|
||||
};
|
||||
use serde_json::json;
|
||||
use sqlx::postgres::PgPoolOptions;
|
||||
use sqlx::PgPool;
|
||||
use std::net::SocketAddr;
|
||||
use std::env;
|
||||
|
||||
#[derive(Clone)]
|
||||
struct AppState {
|
||||
db_pool: PgPool,
|
||||
}
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() {
|
||||
dotenvy::dotenv().expect("Failed to read .env file");
|
||||
|
||||
let database_url = env::var("DATABASE_URL")
|
||||
.expect("DATABASE_URL must be set");
|
||||
|
||||
let db_pool = PgPoolOptions::new()
|
||||
.max_connections(5)
|
||||
.connect(&database_url)
|
||||
.await
|
||||
.expect("Failed to create Postgres connection pool");
|
||||
|
||||
println!("✅ Database connection pool created successfully.");
|
||||
|
||||
let app_state = AppState { db_pool };
|
||||
|
||||
let app = Router::new()
|
||||
.route("/api/health", get(health_checker_handler))
|
||||
.with_state(app_state);
|
||||
|
||||
let addr = SocketAddr::from(([0, 0, 0, 0], 3000));
|
||||
println!("🚀 Server listening on {}", addr);
|
||||
|
||||
let listener = tokio::net::TcpListener::bind(&addr).await.unwrap();
|
||||
axum::serve(listener, app).await.unwrap();
|
||||
}
|
||||
|
||||
async fn health_checker_handler(
|
||||
State(state): State<AppState>,
|
||||
) -> impl IntoResponse {
|
||||
let result = sqlx::query("SELECT 1")
|
||||
.execute(&state.db_pool)
|
||||
.await;
|
||||
|
||||
let (status_code, message) = match result {
|
||||
Ok(_) => (
|
||||
StatusCode::OK,
|
||||
"Database connection is successful.".to_string(),
|
||||
),
|
||||
Err(e) => (
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
format!("Database connection failed: {}", e),
|
||||
),
|
||||
};
|
||||
|
||||
(status_code, Json(json!({ "status": message })))
|
||||
}
|
||||
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue