Configuration files
suggest changeMost programs that run longer than a few seconds need settings: a listen address, a database URL, timeouts, feature switches. A configuration file keeps them out of the code and lets you change them without recompiling.
The usual Go approach is simple:
- describe the configuration as a struct; the struct is the schema
- fill the struct with defaults
- decode the file on top of the defaults
- optionally override values from environment variables and command-line flags
- validate the result once, at startup, and refuse to start if it's wrong
The standard library supports JSON. TOML and YAML need a third-party package, but the pattern is the same for every format.
Choosing a format
| Format | Package | Comments | Notes |
|---|---|---|---|
| JSON | encoding/json (standard library) |
no | strict, no trailing commas, durations need a custom type |
| TOML | github.com/BurntSushi/toml | yes | designed for config files, easy to read and edit by hand |
| YAML | go.yaml.in/yaml/v3 | yes | popular in the Kubernetes / DevOps world, indentation-sensitive |
JSON has no comments, which is a real drawback for files edited by people. TOML is a good default for application config. Use YAML when your users already expect it.
JSON configuration with defaults
The trick for defaults is to decode into a struct that's already filled in. json.Decoder only touches fields that are present in the input, so everything else keeps its default value.
package main
import (
"encoding/json"
"errors"
"fmt"
"io"
"os"
"strings"
"time"
)
// Duration wraps time.Duration so it can be written as "5s" in JSON.
type Duration struct {
time.Duration
}
func (d *Duration) UnmarshalText(b []byte) error {
v, err := time.ParseDuration(string(b))
if err != nil {
return err
}
d.Duration = v
return nil
}
func (d Duration) MarshalText() ([]byte, error) {
return []byte(d.String()), nil
}
type DatabaseConfig struct {
URL string `json:"url"`
MaxConns int `json:"max_conns"`
}
type Config struct {
Addr string `json:"addr"`
LogLevel string `json:"log_level"`
Timeout Duration `json:"timeout"`
Database DatabaseConfig `json:"database"`
AllowedOrigins []string `json:"allowed_origins"`
}
func defaultConfig() Config {
return Config{
Addr: ":8080",
LogLevel: "info",
Timeout: Duration{30 * time.Second},
Database: DatabaseConfig{MaxConns: 10},
}
}
func parseConfig(r io.Reader) (Config, error) {
cfg := defaultConfig()
dec := json.NewDecoder(r)
dec.DisallowUnknownFields()
if err := dec.Decode(&cfg); err != nil {
return Config{}, err
}
if dec.More() {
return Config{}, errors.New("unexpected data after config object")
}
return cfg, nil
}
func loadConfig(path string) (Config, error) {
f, err := os.Open(path)
if err != nil {
return Config{}, err
}
defer f.Close()
cfg, err := parseConfig(f)
if err != nil {
return Config{}, fmt.Errorf("parse %s: %w", path, err)
}
return cfg, nil
}
func main() {
data := `{
"addr": ":9000",
"timeout": "5s",
"database": {"url": "postgres://localhost/app"},
"allowed_origins": ["https://example.com"]
}`
os.WriteFile("config.json", []byte(data), 0o644)
cfg, err := loadConfig("config.json")
if err != nil {
fmt.Println("error:", err)
return
}
fmt.Printf("addr=%s level=%s timeout=%v\n", cfg.Addr, cfg.LogLevel, cfg.Timeout)
fmt.Printf("db=%s max_conns=%d origins=%v\n",
cfg.Database.URL, cfg.Database.MaxConns, cfg.AllowedOrigins)
for _, bad := range []string{
`{"adr": ":9000"}`,
`{"timeout": "5 seconds"}`,
`{"database": {"max_conns": "ten"}}`,
`{"addr": ":9000",}`,
} {
_, err := parseConfig(strings.NewReader(bad))
fmt.Println("error:", err)
}
}
addr=:9000 level=info timeout=5s
db=postgres://localhost/app max_conns=10 origins=[https://example.com]
error: json: unknown field "adr"
error: time: unknown unit " seconds" in duration "5 seconds"
error: json: cannot unmarshal string into Go struct field Config.database.max_conns of type int
error: invalid character '}' looking for beginning of object key string
Things to notice:
log_levelanddatabase.max_connsaren't in the file, so they keep their defaults (info,10). This works for nested structs too.DisallowUnknownFieldsturns a typo likeadrinto an error. Without it the typo is silently ignored and the program runs with the default address, which is much harder to debug.time.Durationis anint64, so plainencoding/jsonexpects nanoseconds ("timeout": 5000000000). The smallDurationwrapper implementsencoding.TextUnmarshalerso people can write"5s"or"1m30s". See Custom JSON marshaling for more on this.- Wrap errors with the file name.
parse config.json: json: unknown field "adr"tells the user exactly where to look.
A missing file returns an error that matches os.ErrNotExist. Decide explicitly what that means for your program: a server should usually refuse to start, while a desktop tool can fall back to the defaults.
TOML
TOML has comments, tables (sections) and arrays of tables, and it decodes time.Duration from strings like "5s" without extra work.
go get github.com/BurntSushi/toml@latest
package main
import (
"fmt"
"os"
"time"
"github.com/BurntSushi/toml"
)
type DatabaseConfig struct {
URL string `toml:"url"`
MaxConns int `toml:"max_conns"`
}
type Backend struct {
Name string `toml:"name"`
URL string `toml:"url"`
Weight int `toml:"weight"`
}
type Config struct {
Addr string `toml:"addr"`
LogLevel string `toml:"log_level"`
Timeout time.Duration `toml:"timeout"`
Database DatabaseConfig `toml:"database"`
Backends []Backend `toml:"backend"`
}
func defaultConfig() Config {
return Config{
Addr: ":8080",
LogLevel: "info",
Timeout: 30 * time.Second,
Database: DatabaseConfig{MaxConns: 10},
}
}
func loadConfig(path string) (Config, error) {
cfg := defaultConfig()
md, err := toml.DecodeFile(path, &cfg)
if err != nil {
return Config{}, fmt.Errorf("parse %s: %w", path, err)
}
if keys := md.Undecoded(); len(keys) > 0 {
return Config{}, fmt.Errorf("parse %s: unknown keys %q", path, keys)
}
return cfg, nil
}
const data = `# Server settings
addr = ":9000"
timeout = "5s"
[database]
url = "postgres://localhost/app"
max_conns = 20
[[backend]]
name = "primary"
url = "http://10.0.0.1:8000"
weight = 3
[[backend]]
name = "fallback"
url = "http://10.0.0.2:8000"
weight = 1
`
func main() {
os.WriteFile("config.toml", []byte(data), 0o644)
cfg, err := loadConfig("config.toml")
if err != nil {
fmt.Println("error:", err)
return
}
fmt.Printf("addr=%s level=%s timeout=%v\n", cfg.Addr, cfg.LogLevel, cfg.Timeout)
fmt.Printf("db=%s max_conns=%d\n", cfg.Database.URL, cfg.Database.MaxConns)
for _, b := range cfg.Backends {
fmt.Printf("backend %s %s weight=%d\n", b.Name, b.URL, b.Weight)
}
os.WriteFile("bad.toml", []byte("[database]\nmax_conn = 5\n"), 0o644)
_, err = loadConfig("bad.toml")
fmt.Println("error:", err)
os.WriteFile("bad2.toml", []byte("addr = :9000\n"), 0o644)
_, err = loadConfig("bad2.toml")
fmt.Println("error:", err)
}
addr=:9000 level=info timeout=5s
db=postgres://localhost/app max_conns=20
backend primary http://10.0.0.1:8000 weight=3
backend fallback http://10.0.0.2:8000 weight=1
error: parse bad.toml: unknown keys ["database.max_conn"]
error: parse bad2.toml: toml: line 1 (last key "addr"): expected value but found ':' instead
The TOML decoder doesn't reject unknown keys by itself. Instead DecodeFile returns toml.MetaData, and md.Undecoded() lists the keys that didn't map to any struct field. Treat a non-empty list as an error (or at least log a warning).
[[backend]] is an array of tables and maps naturally to a []Backend slice.
One gotcha: TOML also accepts an integer for a time.Duration field and treats it as nanoseconds, so timeout = 5 silently becomes 5ns. Validation (shown below) catches this.
To write a config file, for example to generate a sample, use toml.NewEncoder(w).Encode(cfg). Durations are written back as strings like "30s".
YAML
The YAML package formerly at gopkg.in/yaml.v3 is now maintained by the YAML organization under the go.yaml.in/yaml/v3 import path. See also the YAML chapter.
go get go.yaml.in/yaml/v3@latest
package main
import (
"bytes"
"errors"
"fmt"
"io"
"os"
"time"
"go.yaml.in/yaml/v3"
)
type DatabaseConfig struct {
URL string `yaml:"url"`
MaxConns int `yaml:"max_conns"`
}
type Config struct {
Addr string `yaml:"addr"`
LogLevel string `yaml:"log_level"`
Timeout time.Duration `yaml:"timeout"`
Database DatabaseConfig `yaml:"database"`
AllowedOrigins []string `yaml:"allowed_origins"`
}
func defaultConfig() Config {
return Config{
Addr: ":8080",
LogLevel: "info",
Timeout: 30 * time.Second,
Database: DatabaseConfig{MaxConns: 10},
}
}
func loadConfig(path string) (Config, error) {
data, err := os.ReadFile(path)
if err != nil {
return Config{}, err
}
cfg := defaultConfig()
dec := yaml.NewDecoder(bytes.NewReader(data))
dec.KnownFields(true)
// io.EOF means the file is empty (or only comments): keep the defaults
if err := dec.Decode(&cfg); err != nil && !errors.Is(err, io.EOF) {
return Config{}, fmt.Errorf("parse %s: %w", path, err)
}
return cfg, nil
}
const data = `addr: ":9000"
timeout: 5s
database:
url: postgres://localhost/app
allowed_origins:
- https://example.com
- https://www.example.com
`
func main() {
os.WriteFile("config.yaml", []byte(data), 0o644)
cfg, err := loadConfig("config.yaml")
if err != nil {
fmt.Println("error:", err)
return
}
fmt.Printf("addr=%s level=%s timeout=%v\n", cfg.Addr, cfg.LogLevel, cfg.Timeout)
fmt.Printf("db=%s max_conns=%d origins=%v\n",
cfg.Database.URL, cfg.Database.MaxConns, cfg.AllowedOrigins)
os.WriteFile("bad.yaml", []byte("database:\n maxconns: 5\n"), 0o644)
_, err = loadConfig("bad.yaml")
fmt.Println("error:", err)
os.WriteFile("bad2.yaml", []byte("timeout: soon\n"), 0o644)
_, err = loadConfig("bad2.yaml")
fmt.Println("error:", err)
}
addr=:9000 level=info timeout=5s
db=postgres://localhost/app max_conns=10 origins=[https://example.com https://www.example.com]
error: parse bad.yaml: yaml: unmarshal errors:
line 2: field maxconns not found in type main.DatabaseConfig
error: parse bad2.yaml: yaml: unmarshal errors:
line 1: cannot unmarshal !!str `soon` into time.Duration
yaml.Unmarshal ignores unknown keys; use a Decoder with KnownFields(true) to reject them. Errors include line numbers, which helps a lot with deeply nested YAML.
Without a yaml:"..." tag, the key is the lowercased field name (MaxConns becomes maxconns, not max_conns), so always add tags.
Validation
Decoding only checks types. A config can be well-formed and still wrong: an empty database URL, a negative pool size, a log level nobody understands. Give the config struct a Validate method and call it once at startup.
Use errors.Join to report every problem at once instead of making the user fix them one at a time:
func (c *Config) Validate() error {
var errs []error
if c.Addr == "" {
errs = append(errs, errors.New("addr is required"))
}
if !slices.Contains([]string{"debug", "info", "warn", "error"}, c.LogLevel) {
errs = append(errs, fmt.Errorf("log_level: invalid value %q", c.LogLevel))
}
if c.Timeout < time.Second {
errs = append(errs, fmt.Errorf("timeout: must be at least 1s, got %v", c.Timeout))
}
if c.DBURL == "" {
errs = append(errs, errors.New("db_url is required"))
}
if c.MaxConns < 1 || c.MaxConns > 1000 {
errs = append(errs, fmt.Errorf("max_conns: must be 1-1000, got %d", c.MaxConns))
}
return errors.Join(errs...) // nil if errs is empty
}
The output for a bad config looks like this:
invalid config:
log_level: invalid value "verbose"
timeout: must be at least 1s, got 100ms
db_url is required
max_conns: must be 1-1000, got 0
Layering: defaults, file, environment, flags
Real programs usually combine several sources, each overriding the previous one:
- defaults in code
- the config file
- environment variables (convenient in containers and CI, see Environment variables)
- command-line flags (handy for one-off runs)
The subtle part is flags. A flag's default value must not overwrite a value from the file. flag.FlagSet.Visit calls a function only for flags that were actually set on the command line, which solves this neatly.
type Config struct {
Addr string `json:"addr"`
LogLevel string `json:"log_level"`
Timeout time.Duration `json:"timeout"` // nanoseconds in JSON; use the Duration wrapper in real code
DBURL string `json:"db_url"`
MaxConns int `json:"max_conns"`
}
func defaultConfig() Config {
return Config{Addr: ":8080", LogLevel: "info", Timeout: 30 * time.Second, MaxConns: 10}
}
// applyFile overlays values from a JSON file. A missing file is not an error.
func applyFile(cfg *Config, path string) error {
data, err := os.ReadFile(path)
if errors.Is(err, os.ErrNotExist) {
return nil
}
if err != nil {
return err
}
if err := json.Unmarshal(data, cfg); err != nil {
return fmt.Errorf("parse %s: %w", path, err)
}
return nil
}
// applyEnv overlays values from APP_* environment variables.
func applyEnv(cfg *Config) error {
if v, ok := os.LookupEnv("APP_ADDR"); ok {
cfg.Addr = v
}
if v, ok := os.LookupEnv("APP_LOG_LEVEL"); ok {
cfg.LogLevel = strings.ToLower(v)
}
if v, ok := os.LookupEnv("APP_TIMEOUT"); ok {
d, err := time.ParseDuration(v)
if err != nil {
return fmt.Errorf("APP_TIMEOUT: %w", err)
}
cfg.Timeout = d
}
if v, ok := os.LookupEnv("APP_DB_URL"); ok {
cfg.DBURL = v
}
if v, ok := os.LookupEnv("APP_MAX_CONNS"); ok {
n, err := strconv.Atoi(v)
if err != nil {
return fmt.Errorf("APP_MAX_CONNS: %w", err)
}
cfg.MaxConns = n
}
return nil
}
func load(args []string) (Config, error) {
fs := flag.NewFlagSet("app", flag.ContinueOnError)
configPath := fs.String("config", "config.json", "path to config file")
addr := fs.String("addr", "", "listen address")
logLevel := fs.String("log-level", "", "debug, info, warn or error")
timeout := fs.Duration("timeout", 0, "request timeout")
if err := fs.Parse(args); err != nil {
return Config{}, err
}
cfg := defaultConfig()
if err := applyFile(&cfg, *configPath); err != nil {
return Config{}, err
}
if err := applyEnv(&cfg); err != nil {
return Config{}, err
}
// only flags given on the command line override the other sources
fs.Visit(func(f *flag.Flag) {
switch f.Name {
case "addr":
cfg.Addr = *addr
case "log-level":
cfg.LogLevel = *logLevel
case "timeout":
cfg.Timeout = *timeout
}
})
if err := cfg.Validate(); err != nil {
return Config{}, fmt.Errorf("invalid config:\n%w", err)
}
return cfg, nil
}
func main() {
os.WriteFile("config.json", []byte(`{"addr": ":9000", "db_url": "postgres://localhost/app"}`), 0o644)
os.Setenv("APP_LOG_LEVEL", "DEBUG")
cfg, err := load([]string{"-timeout", "10s"})
fmt.Printf("%+v %v\n", cfg, err)
cfg, err = load([]string{"-addr", ":7000"})
fmt.Printf("%+v %v\n", cfg, err)
}
{Addr::9000 LogLevel:debug Timeout:10s DBURL:postgres://localhost/app MaxConns:10} <nil>
{Addr::7000 LogLevel:debug Timeout:30s DBURL:postgres://localhost/app MaxConns:10} <nil>
In the first run addr comes from the file, log_level from the environment and timeout from the flag. In the second run -timeout wasn't given, so the default of 30s survives even though the flag's own default is 0.
load takes args instead of reading os.Args directly, which makes it easy to test. In main call it as load(os.Args[1:]).
Writing applyEnv by hand is tedious for large configs. Libraries like caarlos0/env fill a struct from environment variables based on struct tags (env:"APP_ADDR"), and spf13/viper or knadh/koanf implement the whole layering scheme. For a handful of settings, the explicit code above is easier to understand.
Where to put the config file
For servers, take the path from a -config flag (or an environment variable) with a sensible default such as /etc/myapp/config.toml.
For tools and desktop apps, use os.UserConfigDir, which returns the per-user configuration directory for the current OS:
| OS | os.UserConfigDir() |
|---|---|
| Linux | $XDG_CONFIG_HOME or ~/.config |
| macOS | ~/Library/Application Support |
| Windows | %AppData% (e.g. C:\Users\ann\AppData\Roaming) |
Put your files in a subdirectory named after the app.
Saving settings and embedding defaults
Apps that remember user settings also need to write the file. Two techniques are worth knowing:
- ship the default settings as a file embedded in the binary with
//go:embed - write atomically: write to a temp file in the same directory, then rename it over the old one, so a crash or full disk never leaves a truncated file
package main
import (
_ "embed"
"encoding/json"
"errors"
"fmt"
"os"
"path/filepath"
)
//go:embed default_settings.json
var defaultSettings []byte
type Settings struct {
Theme string `json:"theme"`
FontSize int `json:"font_size"`
RecentFiles []string `json:"recent_files"`
}
func settingsPath() (string, error) {
dir, err := os.UserConfigDir()
if err != nil {
return "", err
}
return filepath.Join(dir, "myapp", "settings.json"), nil
}
func loadSettings(path string) (Settings, error) {
var s Settings
if err := json.Unmarshal(defaultSettings, &s); err != nil {
panic(err) // broken embedded file is a bug, not a runtime error
}
data, err := os.ReadFile(path)
if errors.Is(err, os.ErrNotExist) {
return s, nil // first run
}
if err != nil {
return s, err
}
err = json.Unmarshal(data, &s)
return s, err
}
func saveSettings(path string, s Settings) error {
data, err := json.MarshalIndent(s, "", " ")
if err != nil {
return err
}
data = append(data, '\n')
dir := filepath.Dir(path)
if err := os.MkdirAll(dir, 0o755); err != nil {
return err
}
f, err := os.CreateTemp(dir, ".settings-*.tmp")
if err != nil {
return err
}
tmpName := f.Name()
defer os.Remove(tmpName) // fails harmlessly after a successful rename
if _, err := f.Write(data); err != nil {
f.Close()
return err
}
if err := f.Sync(); err != nil {
f.Close()
return err
}
if err := f.Close(); err != nil {
return err
}
return os.Rename(tmpName, path)
}
func main() {
path, err := settingsPath()
if err != nil {
fmt.Println("error:", err)
return
}
s, err := loadSettings(path)
if err != nil {
fmt.Println("error:", err)
return
}
s.FontSize = 16
s.RecentFiles = append(s.RecentFiles, "notes.txt")
if err := saveSettings(path, s); err != nil {
fmt.Println("error:", err)
return
}
data, _ := os.ReadFile(path)
fmt.Print(string(data))
}
With default_settings.json next to the source file:
{
"theme": "light",
"font_size": 13
}
the first run prints:
{
"theme": "light",
"font_size": 16,
"recent_files": [
"notes.txt"
]
}
The temp file must be in the same directory as the target: os.Rename is atomic only within one file system. On Windows, os.Rename also replaces an existing file.
Reloading configuration without a restart
Long-running servers sometimes reload config on SIGHUP. Store the config behind an atomic.Pointer so readers always see a complete, consistent snapshot, and never swap in a config that failed to load or validate:
var current atomic.Pointer[Config]
func main() {
const path = "config.json"
cfg, err := loadConfig(path)
if err != nil {
log.Fatal(err)
}
current.Store(cfg)
hup := make(chan os.Signal, 1)
signal.Notify(hup, syscall.SIGHUP)
go func() {
for range hup {
cfg, err := loadConfig(path)
if err != nil {
log.Printf("reload failed, keeping old config: %v", err)
continue
}
current.Store(cfg)
log.Printf("config reloaded")
}
}()
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
cfg := current.Load() // one snapshot for the whole request
w.Write([]byte(cfg.Greeting + "\n"))
})
log.Fatal(http.ListenAndServe(":8080", nil))
}
Here loadConfig returns a *Config. Treat a loaded *Config as immutable: build a new one and store it instead of modifying fields in place. Some settings, like the listen address, can't change in a running process anyway; for those a restart is simpler. See OS Signals for more on signal handling.
Best practices
- Load and validate once, at startup. Fail fast with a clear message. Don't let a bad value surface as a panic hours later.
- Pass the config (or the parts each component needs) explicitly to constructors rather than storing it in a global. See Dependency injection.
- Reject unknown keys. Typos in config files are common, and silently ignoring them is the worst outcome.
- Keep secrets out of config files checked into version control. Read passwords and API keys from environment variables or a secret manager, and don't print them when logging the effective config.
- Use real types:
time.Durationfor timeouts,intfor counts,[]stringfor lists. Parse strings once in the loader, not throughout the code. - Document every setting with a commented sample config file (another reason to prefer TOML or YAML over JSON).