This is the third installment in our series about dealing with enterprisey needs using rust.
- part 1 was about the initial setup with axum and postgres, logging and dates.
- part 2 was devoted to input validation on incoming Json objects.
Reading environment variables
I realized that the code I put in for part 1 on github already uses the built-in
std::env::var function, but I didn’t mention it in the blog.
std::env::var function returns a
Result that either contains the environment variable, or in the case that it is not found, the default, supplied in
Check out more documentation.
Dotenv is another option. Upon executing
dotenv().ok() it reads a file with called .env (in the current directory, or any parent) and puts the contents in your environment as variables. This might be more convient depending on your circumstances.
dotenv = "0.15.0"
The code is now:
Note that the
unwrap function will abort the program, in case the DATABASE_URL is not found, but I also added .env to the project root, so the program will run just fine (using cargo in the project directory). Of course, when deployed you need to make sure the file can be found and you must supply a environment specific version of it (to the container).
Dotenv also allows variable substitution within .env files, allowing for less duplication.