In Go, you can use environment variables to provide default values for command-line flags using the flag
package. Here's how you can achieve that:
flag
and os
packages.import (
"flag"
"os"
)
flag
package.var (
flagValue = flag.String("flagname", "", "Description of the flag")
)
init
function, you can check if the environment variable is set and use it as the default value for the flag.func init() {
if value := os.Getenv("ENV_FLAGNAME"); value != "" {
flag.Set("flagname", value)
}
}
The init
function is called automatically before the main
function, and here we use the os.Getenv
function to check if the environment variable is set. If set, we call flag.Set
to update the default value for the flag.
main
function.flag.Parse()
Now, when you run your Go program, it will check if the environment variable is set before using it as the flag's default value. If the environment variable is not set, the default value passed in the flag's declaration will be used.
Note: The init
function is called once for each package, so if you have multiple packages with flags, you may need to set the default values individually for each package.