Getting Started
A simple walkthrough to get you running with envfmt in a new Rust project.
This guide will get you started with envfmt
. We’ll make a new Rust project and
use it to expand a simple environment variable.
1. Create a New Project
First, let’s create a new Rust project and add envfmt
as a dependency.
cargo new my-app
cd my-app
cargo add envfmt
This will add the latest version of envfmt
to your Cargo.toml
.
2. Expand an Environment Variable
Now, let’s write some code. Open up src/main.rs
and replace its content with
this:
fn main() {
let rpc_url_config = "https://eth-mainnet.g.alchemy.com/v2/${ALCHEMY_API_KEY}";
let rpc_url = envfmt::format(rpc_url_config).unwrap();
println!("{}", rpc_url);
}
Here, we’re using the envfmt::format()
function. This function looks for
environment variables in your string and replaces them with values from the
environment.
envfmt::format()
returns a Result
, so you need to handle the case where it
fails. This usually happens if a variable isn’t found. For this example, I’ll
just use .unwrap()
, but in a real app, you should probably handle the error
properly.
3. Run It
Let’s run the app from the command line. You need to set the ALCHEMY_API_KEY
environment variable for it to work.
ALCHEMY_API_KEY=my-secret-key cargo run
You should see this output:
https://eth-mainnet.g.alchemy.com/v2/my-secret-key
If you run it without setting ALCHEMU_API_KEY
, the program will panic because
.unwrap()
will fail on a VariableNotFound
error.
$ cargo run
Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.01s
Running `target/debug/my-app`
thread 'main' panicked at src/main.rs:3:50:
called `Result::unwrap()` on an `Err` value: VariableNotFound("ALCHEMY_API_KEY")
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
4. Providing a Default Value
Let’s fix the panic. You can provide a default value for variables that might be missing. This is a good way to make your program more robust.
Change the template string in src/main.rs
to look like this:
fn main() {
let rpc_url_config = "${RPC_URL:-http://localhost:8545}";
let rpc_url = envfmt::format(rpc_url_config).unwrap();
println!("Using RPC URL: {}", rpc_url);
}
The ${VAR:-default}
syntax tells envfmt to use "http://localhost:8545"
if
RPC_URL
is not set in the environment.
Now, run the program again, but this time without setting the variable:
cargo run
The output will be:
Using RPC URL: http://localhost:8545
And if you do provide the variable, it will be used instead:
$ RPC_URL=https://mainnet.infura.io/v3/my-key cargo run
Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.01s
Running `target/debug/my-app`
Using RPC URL: https://mainnet.infura.io/v3/my-key