How to use environment variables as defaults for command-line flags in Go?

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:

  1. Import the flag and os packages.
import ( "flag" "os" )
  1. Define your command-line flag variables using the flag package.
var ( flagValue = flag.String("flagname", "", "Description of the flag") )
  1. In your 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.

  1. Finally, parse the command-line flags in your 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.