Skip to content

Commit

Permalink
Add dev prod example (#55)
Browse files Browse the repository at this point in the history
* Add dev-prod example

* A word

* Fix typo in dotenv_override

Co-authored-by: Christopher Morton <sonro@gmx.com>

* Use std::env::var after explicit dotenv loading

Co-authored-by: Christopher Morton <sonro@gmx.com>

* Incorporate all suggestions

- remove FromStr
- reorder commands

---------

Co-authored-by: Christopher Morton <sonro@gmx.com>
  • Loading branch information
Allan and sonro committed Mar 17, 2023
1 parent b3d79b4 commit 8802f72
Show file tree
Hide file tree
Showing 4 changed files with 59 additions and 0 deletions.
1 change: 1 addition & 0 deletions examples/.env
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
HOST=dev.com
4 changes: 4 additions & 0 deletions examples/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
[workspace]
members = ["*"]
exclude = ["target"]
resolver = "2"
8 changes: 8 additions & 0 deletions examples/dev-prod/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
[package]
name = "example-dev-prod"
version = "0.1.0"
edition = "2021"
publish = false

[dependencies]
dotenvy = { path = "../../dotenv" }
46 changes: 46 additions & 0 deletions examples/dev-prod/src/main.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
use std::{
env,
fmt::{self},
};

#[derive(PartialEq)]
enum AppEnv {
Dev,
Prod,
}

/// A common setup that:
/// - loads from a .env file in dev mode
/// - loads from the envrironment in prod mode
///
/// A few commands to try:
/// 1) `cargo run`
/// 2) `APP_ENV=prod cargo run`
/// 3) `APP_ENV=prod HOST=prod.com cargo run`
fn main() {
let app_env = match env::var("APP_ENV") {
Ok(v) if v == "prod" => AppEnv::Prod,
_ => AppEnv::Dev,
};

println!("Running in {app_env} mode");

if app_env == AppEnv::Dev {
match dotenvy::dotenv() {
Ok(path) => println!(".env read successfully from {}", path.display()),
Err(e) => println!("Could not load .env file: {e}"),
};
}

let host = env::var("HOST").expect("HOST not set");
println!("Host: {host}");
}

impl fmt::Display for AppEnv {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
AppEnv::Dev => write!(f, "dev"),
AppEnv::Prod => write!(f, "prod"),
}
}
}

0 comments on commit 8802f72

Please sign in to comment.