Skip to content

Instantly share code, notes, and snippets.

@sathiyaseelan
Created January 8, 2018 06:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sathiyaseelan/2ff5f941af44b7d7f96e40175df4569c to your computer and use it in GitHub Desktop.
Save sathiyaseelan/2ff5f941af44b7d7f96e40175df4569c to your computer and use it in GitHub Desktop.
Using different .env files for loading environment variables.

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

  1. Create a config struct as below
  2. Access the env values using the config struct
  3. Run the program with current ENVIRONMENT value set

Create Config Struct

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
}

Access env variables using Config Struct

In your go files, you can access the env values as below

cfg := &config.ReadEnv()
fmt.Println(cfg.AppURL)

Run the test with ENVIRONMENT value as test

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

@kinmor06
Copy link

kinmor06 commented Jan 8, 2018

@sathiyaseelan better change ok to check both ENVIRONMENT and if file exists, before using loading it

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment