Skip to Content
DocumentationGuidesConfiguration

Configuration

A scaffolded project reads one file, config.yaml at the project root, and overlays environment variables on top of it. The file holds development defaults and is committed. Secrets and per-environment values come from the environment, in development through a gitignored .env.

Everything on this page is taken from the config.yaml that gofasta new writes and from the AppConfig type in pkg/config that parses it. Where a value is not in the file, the default the loader applies is given.

How loading works

The scaffold’s DI provider set calls the library like this, in app/di/providers/core.go:

func LoadConfig() (*config.AppConfig, error) { return config.LoadConfigWithPrefix("MYAPP_") }

MYAPP_ is the project name you gave gofasta new, uppercased, with anything that is not a letter, digit or underscore dropped. A project created as my-app gets the prefix MYAPP_.

The loader does three things, in order:

  1. Reads config.yaml from the working directory. A missing file is not an error. The loader logs it and continues with the environment and defaults only, which is how a container with no file mounted still boots.
  2. Overlays every environment variable that starts with the prefix. The prefix is stripped, the rest is lowercased and matched against the known keys of AppConfig, so MYAPP_AUTH_JWT_SECRET resolves to auth.jwt_secret even though the key itself contains an underscore. Environment always wins over the file.
  3. Fills any value still empty with the library default listed in the tables below.

The library’s plain config.LoadConfig() is the same function with the prefix GOFASTA_. Scaffolded projects do not call it, and there is no second prefix or fallback: a variable named GOFASTA_DATABASE_HOST is ignored by a project whose prefix is MYAPP_.

Who reads .env

The application binary does not read .env. It reads the process environment. Three things put .env into that environment for you:

  • gofasta dev loads .env (or the file given by --env-file) before starting Air, and reloads it when you restart from the menu.
  • Docker Compose reads .env from the project directory automatically, and the generated compose.yaml passes the secrets through to the app container.
  • The generated Dockerfile header shows the plain docker run form, --env-file .env.

If you run go run ./app/main serve by hand, export the variables yourself or source the file first.

Secrets

Two values must be real before the server will start: auth.jwt_secret and session.secret. They are deliberately empty in config.yaml, because that file is committed. gofasta new generated random values for both into .env, which is gitignored, and .env.example ships them blank:

MYAPP_AUTH_JWT_SECRET= MYAPP_SESSION_SECRET=

At startup cmd/serve.go calls cfg.ValidateSecrets(). If either value is empty or still a known placeholder, the process exits with a message naming the key instead of signing tokens with a public secret. The generated compose.yaml enforces the same thing at the Compose level and refuses to start without them.

Rotate with:

openssl rand -base64 48

Environment variable overrides

Every key in config.yaml can be set as MYAPP_{SECTION}_{KEY}, nested sections joined with underscores:

Config pathEnvironment variable
server.hostMYAPP_SERVER_HOST
server.portMYAPP_SERVER_PORT
database.hostMYAPP_DATABASE_HOST
database.passwordMYAPP_DATABASE_PASSWORD
database.dsnMYAPP_DATABASE_DSN
auth.jwt_secretMYAPP_AUTH_JWT_SECRET
auth.access_token_expiryMYAPP_AUTH_ACCESS_TOKEN_EXPIRY
cache.driverMYAPP_CACHE_DRIVER
cache.redis.hostMYAPP_CACHE_REDIS_HOST
email.smtp.passwordMYAPP_EMAIL_SMTP_PASSWORD
log.levelMYAPP_LOG_LEVEL
log.formatMYAPP_LOG_FORMAT
session.cookie_secureMYAPP_SESSION_COOKIE_SECURE

Durations use Go syntax (15m, 168h). Booleans are true or false.

Two variables in .env.example are not config keys. PORT is read by gofasta dev and Compose for the host-side port mapping and mirrored into the container as MYAPP_SERVER_PORT. REDIS_HOST_PORT and ASYNQMON_HOST_PORT are Compose port mappings for the optional cache and queue-dashboard services.

The sections

project

project: layout: layered # layered or feature

Read by the CLI, not by the application. gofasta g and gofasta refactor use it to know where generated files go. Change it with gofasta refactor, never by hand.

server

server: host: "127.0.0.1" port: "8080" shutdown_timeout: 15s allowed_origins: - "http://localhost:3000" - "http://localhost:8080"
KeyDefault if unsetNotes
host127.0.0.1Loopback keeps macOS from showing a firewall prompt on every rebuild. Containers and servers set MYAPP_SERVER_HOST=0.0.0.0; the generated Dockerfile and Compose files already do.
port8080A string.
shutdown_timeout15sGraceful shutdown deadline.
allowed_origins*CORS origins. The scaffold writes localhost entries; the library default is * only when the list is empty. Do not ship *.

database

The block depends on the --driver you chose at scaffold time. Ports are strings.

PostgreSQL, the default:

database: driver: postgres host: localhost port: "5432" name: myapp_dev user: myapp password: myapp sslmode: disable max_idle: 10 max_open: 100 max_life: 1h degraded_fallback: false

MySQL uses port "3306", SQL Server "1433" with user sa, and ClickHouse "9000" with user default; the other keys are the same. SQLite has no host, port or credentials, and name is the file path:

database: driver: sqlite name: myapp.db
KeyDefault if unsetNotes
driverpostgrespostgres, mysql, sqlite, sqlserver or clickhouse.
dsnemptyWhen set, used verbatim and every key below except driver and the pool settings is ignored. The escape hatch for search_path, a non-UTC time zone, PgBouncer parameters or multi-host failover. Usually set from the environment as MYAPP_DATABASE_DSN.
host, port, user, password, namelocalhost, 5432Connection parameters when dsn is empty.
sslmodedisablePostgreSQL only.
max_idle, max_open, max_life10, 100, 1hConnection pool.
degraded_fallbackfalsefalse refuses to start when the database is unreachable, so a dead database is a visible crash loop rather than a half-alive process. true boots on an in-memory SQLite stub with database endpoints returning 5xx. gofasta dev sets it through the environment when you pick “Run app without db”.

Each driver’s .env.example also carries the connection values, because gofasta dev runs the database in Docker and publishes it on a host port that differs from the in-container port. The comments in that file explain the three layouts: app on the host with the database in Docker, everything in Docker, or everything on the host.

graphql

Present only when the project was scaffolded with --graphql.

graphql: playground_route: /graphql-playground general_route: /graphql playground_enabled: true introspection_enabled: true complexity_limit: 200

The two _enabled flags are false when unset. The scaffold turns them on for development, and deployments/docker/compose.production.yaml turns them off again through the environment. complexity_limit caps the cost of one query; 0 means the default of 200, negative disables the limit.

log

log: level: info # debug, info, warn, error format: text # text or json

Defaults are info and text. .env.example sets MYAPP_LOG_LEVEL=debug for local work. Production normally sets MYAPP_LOG_FORMAT=json.

email

email: provider: smtp # smtp, sendgrid, brevo or resend from_name: Myapp App from_address: noreply@example.com smtp: host: localhost port: 587 use_tls: true # sendgrid: # api_key: SG.your-api-key # brevo: # api_key: xkeysib-your-api-key

smtp also takes username, password and insecure_skip_verify. resend takes api_key. Provider API keys belong in the environment, for example MYAPP_EMAIL_SENDGRID_API_KEY.

auth

auth: jwt_secret: "" # set MYAPP_AUTH_JWT_SECRET in .env access_token_expiry: 15m refresh_token_expiry: 168h rbac_model: configs/rbac_model.conf rbac_policy: configs/rbac_policy.csv
KeyDefault if unsetNotes
jwt_secretplaceholder, rejected at bootSee Secrets above.
access_token_expiry15m
refresh_token_expiry168hSeven days.
rbac_model, rbac_policyconfigs/rbac_model.conf, configs/rbac_policy.csvCasbin model and policy files.
issueremptyWhen set, stamped into minted tokens and required of accepted ones. Set it when several services share one signing secret, otherwise a token minted for one service unlocks the others.

rate_limit

rate_limit: enabled: true rate: "100-S" # 100 requests per second store: memory # memory or redis

On by default. With store: redis, add a redis block (host, port, password, db) under rate_limit; a memory store counts per replica, so the effective limit is multiplied by the number of replicas.

cache

cache: driver: memory # memory or redis # redis: # host: localhost # port: "6379" # password: "" # db: 0

Redis defaults to localhost:6379, database 0. There is no shared top-level redis section: cache, queue and rate limiting each carry their own connection block, so they can point at different instances or databases.

security

security: hsts: true hsts_max_age: 31536000 frame_deny: true content_type_nosniff: true browser_xss_filter: true referrer_policy: "strict-origin-when-cross-origin"

Also accepts content_security_policy and allowed_hosts. These feed the security-headers middleware.

storage

storage: driver: local # local or s3 local: path: ./uploads # s3: # endpoint: s3.amazonaws.com # bucket: my-bucket # access_key: "" # secret_key: "" # region: us-east-1 # use_ssl: true

queue

queue: enabled: false concurrency: 10 queues: default: 1 # redis: # host: localhost # port: "6379" # password: "" # db: 1

Off by default. The queue’s Redis defaults to database 1 so it does not share keys with the cache on the same instance. queues maps queue names to priorities.

websocket, i18n, encryption

websocket: enabled: true i18n: default_language: en locales_dir: locales encryption: key: "" # 32 bytes to enable pkg/encryption

feature_flag

feature_flag: enabled: false config_path: configs/features.yaml

A master switch for pkg/featureflag. When false every flag resolves to the default the caller passed. When true the service evaluates through whichever OpenFeature provider the application registered at startup. There is no features: section of on/off toggles in config.yaml; the GraphQL playground is controlled under graphql, and application-level flags live in configs/features.yaml or the provider you plug in. See the Feature Flags API reference.

session

session: driver: cookie # cookie or filesystem secret: "" # set MYAPP_SESSION_SECRET in .env session_name: myapp_session # filesystem_path: ./sessions cookie_secure: false cookie_http_only: true cookie_same_site: lax # lax, strict or none cookie_max_age: 2592000 # seconds, 30 days

cookie_secure is false so plain-HTTP local development works. The production Compose manifest sets MYAPP_SESSION_COOKIE_SECURE=true. none for cookie_same_site requires cookie_secure: true.

observability

observability: metrics_enabled: true tracing_enabled: false metrics_path: /metrics service_name: myapp

jobs

jobs: - name: example schedule: "0 0 */6 * * *" # six-field cron, seconds first enabled: false

One entry per scheduled job registered in app/jobs/. gofasta g job <name> [cron] adds both the Go file and the entry.

slack, whatsapp, push

Not written by the scaffold, but understood by the loader. Each has a provider key that is empty, meaning disabled, until you set it: slack.provider is webhook or api, whatsapp.provider is ultramsg, twilio or meta, push.provider is fcm. The provider-specific keys are documented on the Slack, WhatsApp and Push reference pages.

deploy

deploy: host: "" # user@server.com method: docker # docker or binary port: 22 path: "" # default /opt/myapp arch: amd64 # amd64 or arm64 health_path: /health/ready health_timeout: 30 keep_releases: 3 strict_host_key: accept-new domain: ""

Read by gofasta deploy, not by the application. health_path points at /health/ready on purpose: it checks database and cache connectivity, where plain /health answers as soon as the process is up. See the deployment guide.

Validating the file

gofasta config schema emits a JSON Schema for config.yaml, generated from the AppConfig type of the library version your project pins. Point your editor at it for completion and inline validation. The command reference shows how.

Accessing configuration in code

Wire provides the whole *config.AppConfig and, through the extractor providers in app/di/providers/core.go, the sub-sections that infrastructure constructors need (*config.DatabaseConfig, *config.AuthConfig, *config.CacheConfig and so on). A service that needs a value asks for the struct it needs:

type ReportService struct { repo interfaces.ReportRepository cfg *config.AppConfig } func NewReportService(repo interfaces.ReportRepository, cfg *config.AppConfig) *ReportService { return &ReportService{repo: repo, cfg: cfg} } func (s *ReportService) publicBase() string { return "http://" + s.cfg.Server.Host + ":" + s.cfg.Server.Port }

Add the service to the provider set and run gofasta wire.

Environment-specific configuration

Keep config.yaml as the development baseline and change the rest through the environment of each deployment.

Staging:

MYAPP_SERVER_HOST=0.0.0.0 MYAPP_DATABASE_HOST=staging-db.internal MYAPP_DATABASE_PASSWORD=... MYAPP_AUTH_JWT_SECRET=... MYAPP_SESSION_SECRET=...

Production:

MYAPP_SERVER_HOST=0.0.0.0 MYAPP_LOG_FORMAT=json MYAPP_DATABASE_HOST=prod-db.internal MYAPP_DATABASE_PASSWORD=... MYAPP_AUTH_JWT_SECRET=... MYAPP_SESSION_SECRET=... MYAPP_SESSION_COOKIE_SECURE=true MYAPP_CACHE_DRIVER=redis MYAPP_CACHE_REDIS_HOST=prod-redis.internal MYAPP_EMAIL_PROVIDER=sendgrid MYAPP_EMAIL_SENDGRID_API_KEY=...

With the docker deploy method, gofasta deploy copies the project’s .env to the server’s shared directory; with the binary method you manage the environment on the server yourself. See the deployment guide.

Next steps

Last updated on