I like having .env support for local development when developing web service. It's simple, and encourages implementation to consider configurability through environment variables.
More importantly for me it offers development portability whenever I need to move around OS doing development, because I may not have good shell always ready.
This is referential setup to support .env loading in Go that doesn't get in the way of production release to ease project bootstrapping chores.
- Provide
.env.example - Add
.envto.gitignore - Add
.envto.dockerignorefor containerized workflow - Register
-envflag in the project flag parsing logic, prefer allowing to override.envpath with.envas default if unspecified - Prefer
.envloading logic at the beginningmainfunction as early as possible after flag parsing. - Modify
.air.tomlor other live-reload config to-envflag by default. See.air.tomlfor reference - Ensure
.envloading is non-default behavior without the flag
# Load .env in root repository
go run . -env
# Load .env in nested path within repo
go run . -env=nested_env_example/.env