From 7308121fa3efc785bf964b8ab32505ba25513fdc Mon Sep 17 00:00:00 2001 From: Akshay Date: Mon, 24 Aug 2020 13:33:06 +0530 Subject: add cli opts --- src/cli.rs | 35 +++++++++++++++++++++++++++++++++++ src/db.rs | 8 ++++---- src/main.rs | 12 ++++++++---- 3 files changed, 47 insertions(+), 8 deletions(-) create mode 100644 src/cli.rs (limited to 'src') diff --git a/src/cli.rs b/src/cli.rs new file mode 100644 index 0000000..009397d --- /dev/null +++ b/src/cli.rs @@ -0,0 +1,35 @@ +use anyhow::Result; +use lazy_static::lazy_static; + +use std::default::Default; +use std::path::PathBuf; + +pub struct Config { + pub port: u16, + pub db_path: PathBuf, +} + +impl Default for Config { + fn default() -> Self { + Config { + port: 3000, + db_path: "./urls.db_3".into(), + } + } +} + +lazy_static! { + pub static ref CONFIG: Config = parse_args().unwrap_or(Default::default()); +} + +fn parse_args() -> Result { + let mut _a = pico_args::Arguments::from_env(); + return Ok(Config { + port: _a + .opt_value_from_fn("--port", str::parse::)? + .unwrap_or(7878), + db_path: _a + .opt_value_from_str("--database")? + .unwrap_or(PathBuf::from("./urls.db_3")), + }); +} diff --git a/src/db.rs b/src/db.rs index c67e39e..8503b10 100644 --- a/src/db.rs +++ b/src/db.rs @@ -9,7 +9,7 @@ use std::path::Path; pub fn open_connection

(p: P) -> Result where - P: AsRef + fmt::Display, + P: AsRef, { info!("Opened connection to database"); Ok(Connection::open_with_flags( @@ -18,8 +18,8 @@ where )?) } -pub fn init_db + fmt::Display>(p: P) -> Result<()> { - debug!("Looking for database at `{}`", p); +pub fn init_db + fmt::Debug>(p: P) -> Result<()> { + debug!("Looking for database at `{:?}`", p); let conn = open_connection(&p)?; conn.execute( "CREATE TABLE IF NOT EXISTS urls ( @@ -28,6 +28,6 @@ pub fn init_db + fmt::Display>(p: P) -> Result<()> { )", NO_PARAMS, )?; - info!("SQLite3 database `{}` initialized", &p); + info!("SQLite3 database `{:?}` initialized", &p); Ok(()) } diff --git a/src/main.rs b/src/main.rs index 35e686e..5cd3492 100644 --- a/src/main.rs +++ b/src/main.rs @@ -11,14 +11,18 @@ use db::{init_db, open_connection}; mod service; use service::shortner_service; +mod cli; +use cli::CONFIG; + fn main() -> Result<()> { pretty_env_logger::init(); - init_db("./urls.db_3")?; + + init_db(&CONFIG.db_path)?; smol::run(async { - let addr = ([127, 0, 0, 1], 3000).into(); - let service = make_service_fn(move |_| async { + let addr = ([127, 0, 0, 1], CONFIG.port).into(); + let service = make_service_fn(|_| async { Ok::<_, hyper::Error>(service_fn(move |req| { - let db_conn = open_connection("./urls.db_3").unwrap(); + let db_conn = open_connection(&CONFIG.db_path).unwrap(); shortner_service(req, db_conn) })) }); -- cgit v1.2.3