go 13 lines · 1 tab

Safe YAML decoding (KnownFields) for config files

Leah Thompson Jan 2026
1 tab
package config

import (
  "io"

  "gopkg.in/yaml.v3"
)

func DecodeStrict(r io.Reader, dst any) error {
  dec := yaml.NewDecoder(r)
  dec.KnownFields(true)
  return dec.Decode(dst)
}
1 file · go Explain with highlit

YAML configuration is convenient, but it’s also a footgun when typos silently get ignored. I enable KnownFields(true) so unknown keys cause an error, which turns “silent misconfig” into a fast failure. That is especially useful during refactors when fields are renamed. I also decode from an io.Reader so the same code works for local files, embedded config, or S3 objects. In production, I combine this with a strict schema-like struct and a validation step that enforces invariants (timeouts must be > 0, lists must be non-empty, etc.). The goal is to make config errors noisy and actionable, not mysterious. This pattern is small and dependency-light, but it saves a lot of time when debugging environment drift.


Related snips

Share this code

Here's the card — post it anywhere.

Safe YAML decoding (KnownFields) for config files — share card
Link copied