How do I manage environment variables for Go applications?

Managing environment variables in Go applications is essential for configuration and security, allowing developers to separate sensitive data from the source code.

There are several ways to manage environment variables for Go applications:

  • Using the os package: You can access environment variables directly using the os.Getenv function.
  • Using a .env file: Tools like godotenv can load environment variables from a .env file.
  • Using build flags: You can also configure variables during the build process.

Here's a simple example demonstrating how to use the os package to manage environment variables in Go:

package main import ( "fmt" "os" ) func main() { // Set an environment variable os.Setenv("MY_VAR", "Hello, World!") // Get an environment variable value := os.Getenv("MY_VAR") fmt.Println(value) // Output: Hello, World! }

Go applications environment variables configuration management security godotenv os package