Environment variables provide a way to set configuration values for your applications without needing to modify your source code. They are invaluable in managing different configurations for various environments like development, testing, and production.

Understanding Environment Variables

Environment variables are dynamic named values which can affect the way running processes will behave on a computer. In Go, we can use environment variables to manage our configurations effectively.

Setting Environment Variables

Environment variables can be set in different ways depending on your operating system and shell. Below are examples for setting environment variables in Linux/Unix/MacOS and Windows.

Linux/Unix/MacOS

export DATABASE_URL="your_database_url_here"

Windows

set DATABASE_URL=your_database_url_here

Accessing Environment Variables in Go

In Go, the os package provides easy access to environment variables.

Here’s how you can read an environment variable:

package main

import (
  "fmt"
  "os"
)

func main() {
  databaseURL := os.Getenv("DATABASE_URL")
  if databaseURL == "" {
    fmt.Println("DATABASE_URL is not set")
  } else {
    fmt.Printf("Database URL: %s\n", databaseURL)
  }
}

Setting Environment Variables in Go

Sometimes you might need to set an environment variable through your Go application. While this is less common, Go offers a straightforward way to do this with os.Setenv.

package main

import (
  "fmt"
  "os"
)

func main() {
  err := os.Setenv("APP_MODE", "production")
  if err != nil {
    fmt.Println("Error setting environment variable")
  }
  fmt.Println("APP_MODE set to", os.Getenv("APP_MODE"))
}

Best Practices

  • Use Libraries: Consider using a library like godotenv to load environment variables from a .env file for local development.
  • Avoid Hardcoding: Do not hardcode sensitive information like API keys and URLs directly into your code.
  • Use a Configuration Package: Use a configuration management tool or package to help manage your config needs.
  • Documentation: Always document environment variables used in the application.

By effectively using environment variables in Go, you can easily manage your application configurations across multiple environments, improving the portability and security of your application.