Skip to content

Commit 4c36fa6

Browse files
committed
Add custom deserializer to handle ohttp_keys and propagate potential errors
1 parent e8f1069 commit 4c36fa6

File tree

1 file changed

+24
-12
lines changed

1 file changed

+24
-12
lines changed

payjoin-cli/src/app/config.rs

Lines changed: 24 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ pub struct AppConfig {
2020

2121
// v2 only
2222
#[cfg(feature = "v2")]
23+
#[serde(deserialize_with = "deserialize_ohttp_keys_from_path")]
2324
pub ohttp_keys: Option<payjoin::OhttpKeys>,
2425
#[cfg(feature = "v2")]
2526
pub ohttp_relay: Url,
@@ -101,17 +102,7 @@ impl AppConfig {
101102
)?
102103
.set_override_option(
103104
"ohttp_keys",
104-
matches.get_one::<String>("ohttp_keys").and_then(|s| {
105-
std::fs::read(s)
106-
.map_err(|e| {
107-
log::error!("Failed to read ohttp_keys file: {}", e);
108-
ConfigError::Message(format!(
109-
"Failed to read ohttp_keys file: {}",
110-
e
111-
))
112-
})
113-
.ok()
114-
}),
105+
matches.get_one::<String>("ohttp_keys").map(|s| s.as_str()),
115106
)?
116107
};
117108

@@ -128,10 +119,31 @@ impl AppConfig {
128119
Some(("resume", _)) => builder,
129120
_ => unreachable!(), // If all subcommands are defined above, anything else is unreachabe!()
130121
};
131-
132122
let config = builder.build()?;
133123
let app_config: AppConfig = config.try_deserialize()?;
134124
log::debug!("App config: {:?}", app_config);
135125
Ok(app_config)
136126
}
137127
}
128+
129+
#[cfg(feature = "v2")]
130+
fn deserialize_ohttp_keys_from_path<'de, D>(
131+
deserializer: D,
132+
) -> Result<Option<payjoin::OhttpKeys>, D::Error>
133+
where
134+
D: serde::Deserializer<'de>,
135+
{
136+
let path_str: Option<String> = Option::deserialize(deserializer)?;
137+
138+
match path_str {
139+
None => Ok(None),
140+
Some(path) => std::fs::read(path)
141+
.map_err(|e| serde::de::Error::custom(format!("Failed to read ohttp_keys file: {}", e)))
142+
.and_then(|bytes| {
143+
payjoin::OhttpKeys::decode(&bytes).map_err(|e| {
144+
serde::de::Error::custom(format!("Failed to decode ohttp keys: {}", e))
145+
})
146+
})
147+
.map(Some),
148+
}
149+
}

0 commit comments

Comments
 (0)