|
1 |
| -use axum::{routing::get, Router}; |
| 1 | +use anyhow::Result; |
| 2 | +use axum::{extract::State, http::StatusCode, routing::get, Router}; |
| 3 | +use sqlx::{postgres::PgConnectOptions, PgPool}; |
2 | 4 | use std::net::{Ipv4Addr, SocketAddr};
|
3 | 5 | use tokio::net::TcpListener;
|
4 | 6 |
|
| 7 | +struct DatabaseConfig { |
| 8 | + pub host: String, |
| 9 | + pub port: u16, |
| 10 | + pub username: String, |
| 11 | + pub password: String, |
| 12 | + pub database: String, |
| 13 | +} |
| 14 | + |
| 15 | +impl From<DatabaseConfig> for DatabaseConfig { |
| 16 | + fn from(cfg: DatabaseConfig) -> Self { |
| 17 | + Self::new() |
| 18 | + .host(&cfg.host) |
| 19 | + .port(cfg.port) |
| 20 | + .username(&cfg.username) |
| 21 | + .password(&cfg.password) |
| 22 | + .database(&cfg.database) |
| 23 | + } |
| 24 | +} |
| 25 | + |
| 26 | +fn connect_database_with(cfg: DatabaseConfig) -> PgPool { |
| 27 | + PgPool::connect_lazy_with(cfg.into()) |
| 28 | +} |
| 29 | + |
| 30 | +async fn health_check() -> StatusCode { |
| 31 | + StatusCode::OK |
| 32 | +} |
| 33 | + |
5 | 34 | async fn hello_world() -> &'static str {
|
6 | 35 | "Hello, World!"
|
7 | 36 | }
|
8 | 37 |
|
| 38 | +async fn health_check_db(state(db): State<PgPool>) -> StatusCode { |
| 39 | + let connection_result = sqlx::query("SELECT 1").fetch_one(&db).await; |
| 40 | + match connection_result { |
| 41 | + Ok(_) => StatusCode::OK, |
| 42 | + Err(_) => StatusCode::INTERNAL_SERVER_ERROR, |
| 43 | + } |
| 44 | +} |
| 45 | + |
9 | 46 | #[tokio::main]
|
10 |
| -async fn main() { |
11 |
| - let app = Router::new().route("/hello", get(hello_world)); |
| 47 | +async fn main() -> Result<()> { |
| 48 | + let database_cfg = DatabaseConfig { |
| 49 | + host: "localhost".into(), |
| 50 | + port: 5432, |
| 51 | + username: "app".into(), |
| 52 | + password: "passwd".into(), |
| 53 | + database: "app".into(), |
| 54 | + }; |
| 55 | + let conn_pool = connect_lazy_with(database_cfg); |
| 56 | + |
| 57 | + let app = Router::new() |
| 58 | + .route("/hello", get(hello_world)) |
| 59 | + .route("/health_check", get(health_check)) |
| 60 | + .route("/health_db", get(health_check_db)) |
| 61 | + .with_state(conn_pool); |
| 62 | + |
12 | 63 | let addr = SocketAddr::new(Ipv4Addr::LOCALHOST.into(), 8080);
|
13 | 64 | let listener = TcpListener::bind(addr).await.unwrap();
|
14 | 65 | println!("Listening on {}", addr);
|
15 |
| - axum::serve(listener, app).await.unwrap(); |
| 66 | + Ok(axum::serve(listener, app).await?) |
16 | 67 | }
|
| 68 | + |
| 69 | +#[tokio::test] |
| 70 | +async fn health_check_words() { |
| 71 | + let status_code = health_check().await; |
| 72 | + assert_eq!(status_code, StatusCode::OK); |
| 73 | +} |
| 74 | + |
| 75 | +// #[sqlx::test] |
| 76 | +// async fn health_check_db_works(pool: sqlx::PgPool) { |
| 77 | +// // let status_code = health_check_db(State(Pool)).await; |
| 78 | +// // assert_eq!(status_code, StatusCode::OK); |
| 79 | +// } |
0 commit comments