Currently the godotenv library doesn't support loading different .env files such as .env.test for testing .env.staging for staging.
Here's the small snippet, to support different environments file dynamically. Based on the @adamcohen comment.(option 1)
joho/godotenv#43 - Follow this issue for future changes
- Create a config struct as below
- Access the env values using the config struct
- Run the program with current ENVIRONMENT value set
Create a config struct, to hold your environment values and to initiate the struct create a method similar to the one below.(In config.go
)
type Config struct {
AppURL *url.URL
}
func ReadEnv() *Config {
currentEnvironment, ok := os.LookupEnv("ENVIRONMENT")
var err error
if ok == true {
err = godotenv.Load(os.ExpandEnv("$GOPATH/src/github.com/<org_name>/<project-name>/.env."+currentEnvironment))
} else {
err = godotenv.Load()
}
if err != nil {
panic(err)
}
// To load the config values
appURL, _ := os.LookupEnv("APP_URL")
config := &Config{
AppURL: appURL,
}
return config
}
In your go files, you can access the env values as below
cfg := &config.ReadEnv()
fmt.Println(cfg.AppURL)
When you run without setting any ENVIRONMENT
, it will load the .env file.
If you want to run the tests with values in .env.test
, you can run using the below command from any subFolder(by appending the ENVIRONMENT=test
before in your test command)
Example:
$ ENVIRONMENT=test go test -run Test
@sathiyaseelan better change
ok
to check both ENVIRONMENT and if file exists, before using loading it