Skip to content

Instantly share code, notes, and snippets.

@Crazy3lf
Last active July 3, 2019 02:26
Show Gist options
  • Save Crazy3lf/41409bd396d140d4e491bf726a9c0760 to your computer and use it in GitHub Desktop.
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.
AMI_USERNAME="YOUR_AMI_USERNAME"
AMI_PASSWORD="YOUR_AMI_PASSWORD"
AMI_HOST="YOUR_AMI_HOST"
AMI_USERNAME="developer"
AMI_PASSWORD="secret-dev-password"
AMI_HOST="www.developing.com.my"
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