In Go, read secrets with os.LookupEnv or os.Getenv from the standard library and check that required values are set before the server starts. Load a .env file in development with a package such as godotenv, and use your platform's secret store in production.
Read the key from the environment
package main
import (
"log"
"os"
)
func main() {
apiKey, ok := os.LookupEnv("STRIPE_SECRET_KEY")
if !ok || apiKey == "" {
log.Fatal("STRIPE_SECRET_KEY is not set")
}
_ = apiKey // pass to your client; never log it
}Local development
Go has no built-in .env loader. Developers often use github.com/joho/godotenv, direnv or a Makefile target that exports variables before running. Keep the file out of Git. os.Getenv returns an empty string for both unset and empty variables, so use os.LookupEnv when you need to tell them apart.
Production
Inject values at run time from the environment of your container, orchestrator or serverless platform, or mount secrets as files and read them with os.ReadFile. Go builds are static binaries, so never compile secrets in with -ldflags -X or go:embed: they would be readable in the binary and your build logs.
Mistakes to avoid
- Embedding a key with
go:embedor-ldflags "-X main.key=..."; strings in a compiled binary can be extracted withstringsor a debugger. - Logging a config struct with
%+v, which prints secret fields. ImplementString()orLogValue()to redact them. - Passing secrets as command-line flags, which appear in
psoutput and shell history. - Treating
os.Getenvas proof the variable is set; an unset variable returns an empty string.
When an AI agent works on your Go project
Coding agents run inside your project folder, so they can read the same .env file your app reads. BotPassword injects keys at run time instead: the agent calls the run_with intent through the MCP server and the process gets the variables it needs while the agent sees only redacted output. Planned: bpw run, a CLI form of the same.
Frequently asked questions
How do I read an environment variable in Go?
Use os.LookupEnv("NAME"), which also reports whether it was set, or os.Getenv("NAME"), which returns an empty string when unset.
How do I load a .env file in Go?
Use a package such as godotenv in development, calling godotenv.Load() at start-up, and keep the file out of version control. In production, set real environment variables instead.
Should I keep API keys in a .env file for Go?
A .env file that is git-ignored is fine for local development, but every process and every AI coding agent running in that folder can read it. Load secrets into the environment at run time from a password manager or secrets manager instead, so no plaintext file sits in the project.