Go configuration options
31 Jan 2025
Software configuration is for:
- Credentials such as database passwords and API keys—storing them in source code makes it much harder to change or rotate them.
- Settings that vary between environments: test, staging, and production.
If you’re developing in Go the three best tools for configuration are environment variables, flags, and build tags.
Environment variables
Easy to use because you can change it without having to compile and deploy a new app. Taigen uses one database setup for development on my laptop and another for production on a Debian server. To set the database connection string on my laptop I add this to my ~/.zshrc
file:
export TAIGEN_DB='host=localhost port=5432 user=craighoward dbname=taigen sslmode=disable'
And in the Go source code I retrieve it with:
dbStr := os.Getenv("TAIGEN_DB")
In production I use systemd to control Taigen so I add an environment variable to the taigen.service
config file.
Flags: used at runtime
port := flag.Int('port', 80, 'listening port')
flag.Parse()
fmt.Printf("%d", *port)
> ./app -port=42
Build tags: used at compile time
Build tags decide which files should be compiled in the app.
go build -tags "android"