diff --git a/examples/env-substitution b/examples/env-substitution new file mode 100644 index 0000000..cefe6f0 --- /dev/null +++ b/examples/env-substitution @@ -0,0 +1,22 @@ +BASE_URL=http://localhost +PORT=8080 + +# ${VAR} syntax works for all variable names +API_URL=${BASE_URL}:${PORT}/api +HEALTH_URL=${BASE_URL}:${PORT}/health + +# $VAR syntax works when the name contains only alphanumeric characters +GREETING=hello +MESSAGE=$GREETING world + +# Variables defined earlier in the file can be referenced +DB_HOST=db.local +DB_PORT=5432 +DB_NAME=myapp +DATABASE_URL=postgres://${DB_HOST}:${DB_PORT}/${DB_NAME} + +# Single quotes prevent substitution +LITERAL='${BASE_URL} is not expanded here' + +# Escaped dollar sign is treated literally +ESCAPED=\$BASE_URL diff --git a/examples/substitution/Cargo.toml b/examples/substitution/Cargo.toml new file mode 100644 index 0000000..180fba1 --- /dev/null +++ b/examples/substitution/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "substitution-example" +version = "0.1.0" +edition = "2021" +publish = false + +[dependencies] +dotenvy = { path = "../../dotenvy" } diff --git a/examples/substitution/src/main.rs b/examples/substitution/src/main.rs new file mode 100644 index 0000000..92e4d27 --- /dev/null +++ b/examples/substitution/src/main.rs @@ -0,0 +1,40 @@ +//! Demonstrates variable substitution in `.env` files. +//! +//! dotenvy supports referencing previously defined variables using `$VAR` or +//! `${VAR}` syntax. Use `${VAR}` when the variable name contains underscores. +//! Single-quoted values and escaped dollar signs (`\$`) are treated literally. +//! +//! Run with: `cargo run` + +use dotenvy::{EnvLoader, EnvSequence}; +use std::error; + +fn main() -> Result<(), Box> { + let env_map = EnvLoader::with_path("../env-substitution") + .sequence(EnvSequence::InputOnly) + .load()?; + + println!("--- Variable Substitution Demo ---\n"); + + println!("Base values:"); + println!(" BASE_URL = {}", env_map.var("BASE_URL")?); + println!(" PORT = {}", env_map.var("PORT")?); + + println!("\nSubstituted with ${{VAR}} syntax:"); + println!(" API_URL = {}", env_map.var("API_URL")?); + println!(" HEALTH_URL = {}", env_map.var("HEALTH_URL")?); + + println!("\nSubstituted with $VAR syntax:"); + println!(" MESSAGE = {}", env_map.var("MESSAGE")?); + + println!("\nComposed DATABASE_URL:"); + println!(" DATABASE_URL = {}", env_map.var("DATABASE_URL")?); + + println!("\nSingle quotes prevent substitution:"); + println!(" LITERAL = {}", env_map.var("LITERAL")?); + + println!("\nEscaped dollar sign:"); + println!(" ESCAPED = {}", env_map.var("ESCAPED")?); + + Ok(()) +}