Skip to content

Instantly share code, notes, and snippets.

View tjmaynes's full-sized avatar
🔌
Focused

TJ Maynes tjmaynes

🔌
Focused
View GitHub Profile
...
if is_database_connected {
HttpResponse::Ok()
.content_type("application/json")
.body(serde_json::json!({ "database_connected": is_database_connected }).to_string())
} else {
HttpResponse::ServiceUnavailable()
.content_type("application/json")
.body(serde_json::json!({ "database_connected": is_database_connected }).to_string())
}
async fn get_health_status(data: web::Data<AppState>) -> HttpResponse {
let is_database_connected = sqlx::query("SELECT 1")
.fetch_one(&data.db_conn)
.await
.is_ok();
...
async fn get_health_status(data: web::Data<AppState>) -> HttpResponse {
...
use actix_web::{web, App, HttpServer, HttpResponse};
use sqlx::{Pool, Postgres, postgres::PgPoolOptions};
async fn get_health_status() -> HttpResponse {
HttpResponse::Ok()
.content_type("application/json")
.body("Healthy!")
}
struct AppState {
...
let app_state = web::Data::new(AppState {
db_conn: db_conn
});
HttpServer::new(move || {
App::new()
.app_data(app_state.clone()) // <- cloned app_state variable
.route("/health", web::get().to(get_health_status))
})
...
let app_state = web::Data::new(AppState {
db_conn: db_conn
});
...
...
use sqlx::{Pool, Postgres, postgres::PgPoolOptions};
...
struct AppState {
db_conn: Pool<Postgres>
}
...
let db_conn = PgPoolOptions::new()
.max_connections(5)
.connect_timeout(Duration::from_secs(2))
.connect(database_url.as_str()) // <- Use the str version of database_url variable.
.await
.expect("Should have created a database connection");
...
#[actix_web::main]
async fn main() -> std::io::Result<()> {
let database_url = std::env::var("DATABASE_URL").expect("Should set 'DATABASE_URL'");
...
use actix_web::{web, App, HttpServer, HttpResponse};
async fn get_health_status() -> HttpResponse {
HttpResponse::Ok()
.content_type("application/json")
.body("Healthy!")
}
#[actix_web::main]
async fn main() -> std::io::Result<()> {