[Awesome Rust] Use dotenv, dotenv_codegen to loads environment variables from .env file
dotenv
This crate provides a configuration loader in the style of the ruby dotenv - https://github.com/bkeepers/dotenv gem. 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 operating system.
Prerequites
Cargo is the Rust package manager. Cargo downloads your Rust package’s dependencies, compiles your packages, makes distributable packages, and uploads them to crates.io - https://crates.io/, the Rust community’s package registry.
- Install Rust and Cargo
The easiest way to get Cargo is to install the current stable release of Rust by using rustup. Installing Rust using rustup will also install cargo.
On Linux and macOS systems, this is done as follows:
1 | curl https://sh.rustup.rs -sSf | sh |
It will download a script, and start the installation. If everything goes well, you’ll see this appear:
1 | Rust is installed now. Great! |
Installation
Add it into the Cargo.toml:
1 | # Cargo.toml |
Usages
The easiest and most common usage consists on calling dotenv::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.
Examples
A .env file looks like this:
1 | # .env |
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:
1 | extern crate dotenv; |
Variable substitution
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:
1 | # .env |
Dotenv will parse the file, substituting the variables the way it’s described in the comments.
Using the dotenv! macro
Add dotenv_codegen to your dependencies, and add the following to the top of your crate:
1 |
|
Then, in your crate:
1 | fn main() { |
References
[2] dotenv - crates.io: Rust Package Registry - https://crates.io/crates/dotenv
[3] dotenv_codegen - crates.io: Rust Package Registry - https://crates.io/crates/dotenv_codegen