Completed the health check with a db connection test

Signed-off-by: Louis Vallat <louis@louis-vallat.xyz>
This commit is contained in:
Louis Vallat 2021-06-09 16:24:13 +02:00
parent 58f6ddf215
commit 6e886a7952

View File

@ -7,26 +7,36 @@ mod model;
mod route;
mod lib;
use actix_web::{App, HttpServer, Responder, web};
use actix_web::{App, HttpServer, Responder, web, HttpResponse};
use std::env;
use diesel::{PgConnection, Connection};
async fn health() -> impl Responder {
"Healthy"
let database_url = env::var("DATABASE_URL").expect("DATABASE_URL must be set");
match PgConnection::establish(&database_url) {
Ok(_value) => HttpResponse::Ok().body("Healthy"),
Err(_e) => {
eprintln!("Could not connect to PostgreSQL.");
eprintln!("Error connecting to {}", database_url);
HttpResponse::InternalServerError().body("Cannot connect to database.")
}
}
}
#[actix_web::main]
async fn main() -> std::io::Result<()> {
let server_string = format!("{}:{}",
env::var("HOST_IP").unwrap_or("0.0.0.0".to_string()),
env::var("HOST_PORT").unwrap_or("8080".to_string()));
println!("Server will be listening: {}", server_string);
HttpServer::new(|| {
App::new().service(web::scope("/v1")
.configure(route::init_routes)
)
.route("/health", web::get().to(health))
})
.bind(format!("{}:{}",
env::var("HOST_IP").unwrap_or("0.0.0.0".to_string()),
env::var("HOST_PORT").unwrap_or("8080".to_string())
))?
.bind(server_string)?
.run()
.await
}