-
-
Save Crazy3lf/41409bd396d140d4e491bf726a9c0760 to your computer and use it in GitHub Desktop.
Handling .env file with option to override them with flags. This example read .env into a map instead of writing into the OS environment variables.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
AMI_USERNAME="YOUR_AMI_USERNAME" | |
AMI_PASSWORD="YOUR_AMI_PASSWORD" | |
AMI_HOST="YOUR_AMI_HOST" |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
AMI_USERNAME="developer" | |
AMI_PASSWORD="secret-dev-password" | |
AMI_HOST="www.developing.com.my" |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"flag" | |
"fmt" | |
"github.com/joho/godotenv" | |
) | |
var( | |
// parse config flag | |
envFlag = flag.String("env", ".env", "The .env file to load.") | |
usernameFlag = flag.String("u", "", "Username for AMI authentication.") | |
passwordFlag = flag.String("p", "", "Password for AMI authentication.") | |
hostnameFlag = flag.String("h", "", "Hostname for AMI.") | |
) | |
func main() { | |
loadConfig() | |
fmt.Println("after flags") | |
fmt.Println(*usernameFlag) | |
fmt.Println(*passwordFlag) | |
fmt.Println(*hostnameFlag) | |
} | |
func loadConfig() { | |
// parse first to load the env value | |
flag.Parse() | |
// load .env | |
env, _ := godotenv.Read(*envFlag) | |
// set env as flag default | |
_ = flag.Set("u", env["AMI_USERNAME"]) | |
_ = flag.Set("p", env["AMI_PASSWORD"]) | |
_ = flag.Set("h", env["AMI_HOST"]) | |
fmt.Println(*usernameFlag) | |
fmt.Println(*passwordFlag) | |
fmt.Println(*hostnameFlag) | |
// parse flags again to make user input flags override default | |
flag.Parse() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment