0

I'm planning to use godotenv to setup different environments for my project but I am not sure how to switch between files like dev.env, uat.env, prod.env

I want to be able to just pass a value in my Docker command like RUN go build -o my-project --prod . and have godotenv pickup the relative env file - in this case prod.env (assuming this is the correct way.

Also, how can I make sure that the other env files don't get included in the build of a particular env.

zer0
  • 4,657
  • 7
  • 28
  • 49
  • 2
    You can use the `-X` flag to `go build` to [set the value of variables at compile time](https://stackoverflow.com/questions/47509272/how-to-set-package-variable-using-ldflags-x-in-golang-build). You can probably take advantage of that to get what you want. – larsks Sep 08 '21 at 16:44
  • @larsks thank you! That helps. – zer0 Sep 08 '21 at 17:27

2 Answers2

2

I will advice you use the -X flag as suggested by Go Documentation on Command Line

-X importpath.name=value
    Set the value of the string variable in importpath named name to value.
    This is only effective if the variable is declared in the source code either uninitialized or initialized to a constant string expression. -X will not work if the initializer makes a function call or refers to other variables.
    Note that before Go 1.5 this option took two separate arguments.

Such that you can then call any of your .env file referencing it location.

E.g. go build -ldflags="-X 'package_path.variable_name=new_value'"

That is

go build -ldflags "-X 'my/main/config.Version=v1.0.0'" -o $(MY_BIN) $(MY_SRC)
Dharman
  • 30,962
  • 25
  • 85
  • 135
antzshrek
  • 9,276
  • 5
  • 26
  • 43
0

Hard coding your environment at the build stage seems odd to me. You don't want to build a diff image per env, that's wasteful.

The module documentation suggests a better approach:

Existing envs take precedence of envs that are loaded later.

The convention for managing multiple environments (i.e. development, test, production) is to create an env named {YOURAPP}_ENV and load envs in this order:

env := os.Getenv("FOO_ENV")
if "" == env {
  env = "development"
}

godotenv.Load(".env." + env + ".local")
if "test" != env {
  godotenv.Load(".env.local")
}
godotenv.Load(".env." + env)
godotenv.Load() // The Original .env
Chen A.
  • 10,140
  • 3
  • 42
  • 61