Skip to content

Instantly share code, notes, and snippets.

View tjmaynes's full-sized avatar
🔌
Focused

TJ Maynes tjmaynes

🔌
Focused
View GitHub Profile
[dependencies]
actix-web = "4.0.0-beta.8"
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
sqlx = { version = "0.5.7", features = [ "runtime-actix-native-tls", "postgres" ] }
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<()> {
#[actix_web::main]
async fn main() -> std::io::Result<()> {
let database_url = std::env::var("DATABASE_URL").expect("Should set 'DATABASE_URL'");
...
...
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");
...
...
use sqlx::{Pool, Postgres, postgres::PgPoolOptions};
...
struct AppState {
db_conn: Pool<Postgres>
}
...
let app_state = web::Data::new(AppState {
db_conn: db_conn
});
...
...
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))
})
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 {
async fn get_health_status(data: web::Data<AppState>) -> HttpResponse {
...
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();
...