0
votes

I'm trying to load the environment variable with calling godotenv.Load in my main method but the problem is that I have init functions in other packages and they run before the environment variables are loaded from .env file, therefore causing trouble.

Is there any workaround for this?

1
There is an obvious workaround: do not load .env files by programs which are supposed to use the environment variables set by such files. If you note that environment variables as a form of configuration was actually invented to affect the behaviour of the programs, and hence such variables were to set up before a program using them runs. Trying to set environment variables in a running process has no sense: you could just as well tweak internal program's variables. - kostix
Sure, there's another workaround: initialize the environment variables and then re-execute the program so that it sees them when it's run. But this design is very broken due to the reasons already explained. - kostix
@kostix Fair point, but still there is an issue with envconfig that initializes a struct based on the environment variables. Are these modules all redundant? It seems then the only option is os.Getenv - Mohsen Kamrani
What is envconfig? I do not quite get what you're asking for. - kostix
Ah, you mean github.com/kelseyhightower/envconfig? If yes, I still don't get what you're asking for. envconfig is a tool for "mass-application" of the values of environment variables to fields of structs—nothing more; that is, it can spare you writing a bit of boilerplate code and internally it surely calls os.Getenv or the like. But this is not concerned with how these environment variables are set because env. vars are supposed to be set before a program which reads them actually starts. - kostix

1 Answers

0
votes

Golang initializes imported packages before anything else. This causes the problem with setting the envvars in the main() function. Luckily Godotenv has an autoloader function that uses import declaration to autoload an .env file from project root folder. Imports are evaluated in declaration order, so you must declare the import before all packages that depend on the envvars:

import _ "github.com/joho/godotenv/autoload"

To import a package solely for its initialization, you should use the blank identifier as explicit package name.