Skip to content

Commit eede95d

Browse files
committed
Add command line arguments + config parsing
1 parent d9b5693 commit eede95d

4 files changed

Lines changed: 56 additions & 1 deletion

File tree

‎payjoin-service/Cargo.toml‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,8 +20,11 @@ default = []
2020

2121
[dependencies]
2222
anyhow = "1.0"
23+
clap = { version = "4.5", features = ["derive", "env"] }
24+
config = "0.15"
2325
ohttp-relay = { path = "../ohttp-relay" }
2426
payjoin-directory = { path = "../payjoin-directory" }
27+
serde = { version = "1.0", features = ["derive"] }
2528
tokio = { version = "1.47", features = ["full"] }
2629
tracing = "0.1"
2730
tracing-subscriber = { version = "0.3", features = ["env-filter"] }

‎payjoin-service/src/cli.rs‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
use std::env;
2+
3+
use clap::Parser;
4+
5+
#[derive(Debug, Parser)]
6+
#[command(
7+
version = env!("CARGO_PKG_VERSION"),
8+
about = "Payjoin Directory and OHTTP Relay service",
9+
long_about = None,
10+
)]
11+
pub struct Cli {
12+
#[arg(long, short = 'p', env = "PJ_PORT", help = "The port to bind [default: 8080]")]
13+
pub port: Option<u16>,
14+
}

‎payjoin-service/src/config.rs‎

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
use config::builder::DefaultState;
2+
use config::{ConfigError, File, FileFormat};
3+
use serde::Deserialize;
4+
5+
use crate::cli::Cli;
6+
7+
type Builder = config::builder::ConfigBuilder<DefaultState>;
8+
9+
#[derive(Debug, Clone, Deserialize)]
10+
pub struct Config {
11+
pub port: u16,
12+
}
13+
14+
impl Config {
15+
pub fn new(cli: &Cli) -> Result<Self, ConfigError> {
16+
let mut config = config::Config::builder();
17+
config = add_defaults(config, cli)?;
18+
19+
config = config.add_source(File::new("config.toml", FileFormat::Toml).required(false));
20+
21+
let built_config = config.build()?;
22+
23+
Ok(Config { port: built_config.get("port")? })
24+
}
25+
}
26+
27+
fn add_defaults(config: Builder, cli: &Cli) -> Result<Builder, ConfigError> {
28+
let config = config.set_default("port", 8080)?.set_override_option("port", cli.port)?;
29+
30+
Ok(config)
31+
}

‎payjoin-service/src/main.rs‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,18 @@
1+
use clap::Parser;
12
use tracing_subscriber::filter::LevelFilter;
23
use tracing_subscriber::EnvFilter;
34

5+
mod cli;
6+
mod config;
7+
48
#[tokio::main]
59
async fn main() -> anyhow::Result<()> {
610
init_tracing();
711

8-
todo!("Everything")
12+
let cli = cli::Cli::parse();
13+
let config = config::Config::new(&cli)?;
14+
15+
todo!("Initialize services and start server on port {}", config.port)
916
}
1017

1118
fn init_tracing() {

0 commit comments

Comments
 (0)