Store secrets in environment variables or external vaults and access them via os.Getenv in Go, never hardcoding them in source files.
Go does not provide a built-in secrets manager; you must store sensitive data in environment variables or a dedicated vault and access them at runtime. Never hardcode secrets in your source code. Use os.Getenv to retrieve values like API keys or database passwords from the environment, ensuring they are not committed to version control.
import "os"
func main() {
apiKey := os.Getenv("API_KEY")
if apiKey == "" {
panic("API_KEY environment variable is required")
}
// Use apiKey securely
}
Think of secrets like passwords or API keys as physical keys you keep in a safe, not written on a sticky note on your computer. In Go, you should never write these keys directly into your code files. Instead, you store them in a secure place outside your code (like a cloud vault or a system setting) and tell your program where to find them when it runs. This way, if someone steals your code, they don't get your secrets.