📖 2 min read (~ 400 words).

Reject unknown fields

The task: a configuration file with a typo in a key should fail to load, and say where the typo is.

The type and the file

type Config struct {
	Name string `yaml:"name"`
	Port int    `yaml:"port"`
}

Full source: docs/examples/decoding/unknownfields/example_test.go

// "prot" and "hots" are typos: Config has no such fields.
const src = `name: api
prot: 8080
hots: example.com
port: 9090
`

Full source: docs/examples/decoding/unknownfields/example_test.go

By default, Unmarshal ignores a key no field takes: this file decodes with no error and Port set to 9090. The typos go unnoticed.

Decode with DisallowUnknownField

var c Config
err := codec.Unmarshal([]byte(src), &c, codec.DisallowUnknownField())
fmt.Println(err)

Full source: docs/examples/decoding/unknownfields/example_test.go

[2:1] unknown field "prot"
   1 | name: api
>  2 | prot: 8080
       ^
   3 | hots: example.com
   4 | port: 9090

Full source: docs/examples/decoding/unknownfields/example_test.go

The error names the first unknown key and its position, [line:column], and draws the lines around it. codec.Strict() sets the same option and nothing else.

The decode goes on

var c Config
_ = codec.Unmarshal([]byte(src), &c, codec.DisallowUnknownField())
fmt.Printf("%+v\n", c)

Full source: docs/examples/decoding/unknownfields/example_test.go

{Name:api Port:9090}

Full source: docs/examples/decoding/unknownfields/example_test.go

An unknown field is an error about one field. The decoder records the first one and goes on filling the fields it knows, so Port still holds 9090. The error stops nothing else in the document. See Errors.

Read the position

A linter or an editor wants the position as data, not as text:

// errors.Is matches the kind; errors.AsType gives the *errors.Error with its token.
if errors.Is(err, yerrors.ErrUnknownField) {
	if e, ok := errors.AsType[*yerrors.Error](err); ok {
		pos := e.GetToken().Position
		fmt.Printf("config.yaml:%d:%d: %s\n", pos.Line, pos.Column, e.GetMessage())
	}
}

Full source: docs/examples/decoding/unknownfields/example_test.go

config.yaml:2:1: unknown field "prot"

Full source: docs/examples/decoding/unknownfields/example_test.go

errors.Is matches the kind against errors.ErrUnknownField. GetToken returns the token the error stands on, and GetMessage the message without the position or the source.

Variations

  • Only the first typo is reported. hots in the file above is not mentioned. Fix one, run again.
  • Keys from an embedding format. codec.AllowFieldPrefixes("x-") lets keys with that prefix through while unknown fields are rejected.