Support setting environment variables in JSON config

This commit is contained in:
eric
2026-03-13 16:59:51 +08:00
parent 822889c78a
commit 12f77224c6
4 changed files with 32 additions and 1 deletions

View File

@@ -514,6 +514,7 @@ pub struct Router {
#[derive(Serialize, Deserialize, Debug, Clone, Default)]
pub struct Config {
pub log: Option<Log>,
pub env: Option<HashMap<String, String>>,
pub inbounds: Option<Vec<Inbound>>,
pub outbounds: Option<Vec<Outbound>>,
pub router: Option<Router>,

View File

@@ -20,8 +20,21 @@ pub fn to_internal(config: Config) -> Result<internal::Config> {
common::to_internal(config)
}
fn apply_env(config: &common::Config) {
if let Some(env) = &config.env {
for (k, v) in env {
if !k.trim().is_empty() {
std::env::set_var(k, v);
}
}
}
}
pub fn json_from_string(config: &str) -> Result<common::Config> {
serde_json::from_str(config).map_err(|e| anyhow!("deserialize json config failed: {}", e))
let config: common::Config = serde_json::from_str(config)
.map_err(|e| anyhow!("deserialize json config failed: {}", e))?;
apply_env(&config);
Ok(config)
}
pub fn from_string(s: &str) -> Result<internal::Config> {

View File

@@ -143,6 +143,22 @@ fn test_dns_config() {
assert_eq!(dns.servers.as_ref().unwrap()[0], "1.1.1.1");
}
#[test]
fn test_env_config_sets_process_env() {
let key = "LEAF_JSON_ENV_TEST_KEY";
std::env::remove_var(key);
let json_str = r#"
{
"env": {
"LEAF_JSON_ENV_TEST_KEY": "json-env-value"
}
}
"#;
let _ = crate::config::json::json_from_string(json_str).unwrap();
assert_eq!(std::env::var(key).unwrap(), "json-env-value");
std::env::remove_var(key);
}
#[test]
fn test_tls_outbound_ech_config_mapping() {
let json_str = r#"

View File

@@ -127,6 +127,7 @@ fn new_socks_outbound(
}];
let config = leaf::config::json::Config {
log: None,
env: None,
inbounds: None,
outbounds: Some(outbounds),
router: None,