A fork of dotenv, designed to work better with modern Rust, and design patterns.
Achtung! This is a v0.* version! Expect bugs and issues all around. Submitting pull requests and issues is highly encouraged!
Quoting bkeepers/dotenv:
Storing configuration in the environment is one of the tenets of a twelve-factor app. Anything that is likely to change between deployment environments–such as resource handles for databases or credentials for external services–should be extracted from the code into environment variables.
This library is meant to be used on development or testing environments in
which setting environment variables is not practical. It loads environment
variables from a .env
file, if available, and mashes those with the actual
environment variables provided by the operative system.
The easiest and most common usage consists on calling rotenv::dotenv
when the
application starts, which will load environment variables from a file named
.env
in the current directory or any of its parents; after that, you can just call
the environment-related method you need as provided by std::os
.
If you need finer control about the name of the file or its location, you can
use the from_filename
and from_path
methods provided by the crate.
dotenv_codegen
provides the dotenv!
macro, which
behaves identically to env!
, but first tries to load a .env
file at compile
time.
A .env
file looks like this:
```sh
REDISADDRESS=localhost:6379 MEANINGOF_LIFE=42 ```
You can optionally prefix each line with the word export
, which will
conveniently allow you to source the whole file on your shell.
A sample project using Dotenv would look like this:
```rust extern crate dotenv;
use rotenv::dotenv; use std::env;
fn main() { dotenv().ok();
for (key, value) in env::vars() {
println!("{}: {}", key, value);
}
} ```
It's possible to reuse variables in the .env
file using $VARIABLE
syntax.
The syntax and rules are similar to bash ones, here's the example:
```sh
VAR=one VAR_2=two
RESULT=$NOPE #value: '' (empty string)
RESULT=$VAR #value: 'one'
RESULT="$VAR" #value: 'one'
RESULT=${VAR} #value: 'one'
RESULT=$VAR2 #value: 'one2' since $ with no curly braces stops after first non-alphanumeric symbol RESULT=${VAR_2} #value: 'two'
RESULT='$VAR' #value: '$VAR' RESULT=\$VAR #value: '$VAR'
RESULT=$PATH #value: the contents of the $PATH environment variable PATH="My local variable value" RESULT=$PATH #value: the contents of the $PATH environment variable, even though the local variable is defined ```
Dotenv will parse the file, substituting the variables the way it's described in the comments.
dotenv!
macroAdd dotenv_codegen
to your dependencies, and add the following to the top of
your crate:
```rust
extern crate dotenv_codegen; ```
Then, in your crate:
rust
fn main() {
println!("{}", dotenv!("MEANING_OF_LIFE"));
}