From c884eae54ce5c027a951ac2e3e9715cc2a63d45f Mon Sep 17 00:00:00 2001 From: Mariano Riefolo Date: Sat, 10 Aug 2024 20:37:51 +0200 Subject: [PATCH] feat: allow to use custom port with a .env file --- .gitignore | 1 + Cargo.lock | 7 +++++++ Cargo.toml | 1 + src/main.rs | 8 +++++++- 4 files changed, 16 insertions(+), 1 deletion(-) diff --git a/.gitignore b/.gitignore index bf7a792..f7b8bee 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,3 @@ /target database.db +.env diff --git a/Cargo.lock b/Cargo.lock index d66192d..2e87c3b 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -212,6 +212,12 @@ dependencies = [ "subtle", ] +[[package]] +name = "dotenvy" +version = "0.15.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1aaf95b3e5c8f23aa320147307562d361db0ae0d51242340f558153b4eb2439b" + [[package]] name = "fallible-iterator" version = "0.3.0" @@ -683,6 +689,7 @@ version = "0.1.0" dependencies = [ "argon2", "axum", + "dotenvy", "rand", "rusqlite", "tokio", diff --git a/Cargo.toml b/Cargo.toml index 27b68f7..96e11d7 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -6,6 +6,7 @@ edition = "2021" [dependencies] argon2 = { version = "0.5.3", features = ["password-hash", "rand"] } axum = "0.7.5" +dotenvy = "0.15.7" rand = "0.8.5" rusqlite = "0.32.1" tokio = { version = "1.39.2", features = ["full"] } diff --git a/src/main.rs b/src/main.rs index c21a65e..24c3267 100644 --- a/src/main.rs +++ b/src/main.rs @@ -10,9 +10,15 @@ async fn main() { let connection = Connection::open("database.db").expect("Failed to open database"); db::init(&connection).expect("Failed to create database"); + dotenvy::dotenv().ok(); + let app = Router::new(); - let addr = SocketAddr::from(([0, 0, 0, 0], 3000)); + let port = std::env::var("PORT") + .unwrap_or_else(|_| "3000".to_string()) + .parse() + .expect("PORT must be an unsigned number"); + let addr = SocketAddr::from(([0, 0, 0, 0], port)); let listener = tokio::net::TcpListener::bind(&addr).await.unwrap(); axum::serve(listener, app).await.unwrap();