📖 4 min read (~ 700 words).

Validate on decode

The task: reject a configuration whose values are out of range, and report the line of the bad value, as a syntax error would be reported.

The types and the file

type Listener struct {
	Host string `yaml:"host"`
	Port int    `yaml:"port"`
}

type Config struct {
	Name      string     `yaml:"name"`
	Listeners []Listener `yaml:"listeners"`
}

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

const src = `name: api
listeners:
  - host: a.example.com
    port: 8080
  - host: b.example.com
    port: 70000
`

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

A validator

var errPort = errors.New("port out of range")

// checkPort is called with each struct the decoder fills, by value.
func checkPort(v any) error {
	l, ok := v.(Listener)
	if !ok || (l.Port >= 1 && l.Port <= 65535) {
		return nil
	}

	return fmt.Errorf("%w: %d", errPort, l.Port)
}

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

codec.Validator calls the function once for each struct the decoder fills, after it is filled, with the struct by value: here once per Listener, then once for the Config. A type switch or a type assertion picks the structs the function checks.

Decode with it

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

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

[5:5] port out of range: 70000
   2 | listeners:
   3 |   - host: a.example.com
   4 |     port: 8080
>  5 |   - host: b.example.com
           ^
   6 |     port: 70000

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

The decoder places the error at the mapping of the struct the validator rejected, the second listener, at line 5, and draws the source around it.

Match the error

fmt.Println(errors.Is(err, yerrors.ErrValidation))
fmt.Println(errors.Is(err, errPort))
fmt.Printf("%+v\n", c.Listeners)

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

true
true
[{Host:a.example.com Port:8080} {Host:b.example.com Port:70000}]

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

The error matches errors.ErrValidation, and it wraps the validator’s own error, so errors.Is also reaches errPort. The value is decoded in full: the validator runs after the struct is filled and changes nothing in it.

Point at the field

An error that is a slice of values with a StructField() string method points at the value of the first field it names:

// fieldError names the Go field it is about, so the decoder can point at that field's value.
type fieldError struct {
	field, msg string
}

func (e fieldError) Error() string       { return e.field + ": " + e.msg }
func (e fieldError) StructField() string { return e.field }

// fieldErrors is a slice of them, as github.com/go-playground/validator/v10 returns.
type fieldErrors []fieldError

func (es fieldErrors) Error() string {
	msgs := make([]string, len(es))
	for i, e := range es {
		msgs[i] = e.Error()
	}

	return strings.Join(msgs, "; ")
}

func checkPortField(v any) error {
	l, ok := v.(Listener)
	if !ok || (l.Port >= 1 && l.Port <= 65535) {
		return nil
	}

	return fieldErrors{{field: "Port", msg: fmt.Sprintf("%d is out of range", l.Port)}}
}

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

// fieldError names the Go field it is about, so the decoder can point at that field's value.
type fieldError struct {
	field, msg string
}

func (e fieldError) Error() string       { return e.field + ": " + e.msg }
func (e fieldError) StructField() string { return e.field }

// fieldErrors is a slice of them, as github.com/go-playground/validator/v10 returns.
type fieldErrors []fieldError

func (es fieldErrors) Error() string {
	msgs := make([]string, len(es))
	for i, e := range es {
		msgs[i] = e.Error()
	}

	return strings.Join(msgs, "; ")
}

func checkPortField(v any) error {
	l, ok := v.(Listener)
	if !ok || (l.Port >= 1 && l.Port <= 65535) {
		return nil
	}

	return fieldErrors{{field: "Port", msg: fmt.Sprintf("%d is out of range", l.Port)}}
}

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

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

[6:11] Port: 70000 is out of range
   3 |   - host: a.example.com
   4 |     port: 8080
   5 |   - host: b.example.com
>  6 |     port: 70000
                 ^

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

StructField returns the Go field name, Port, and the decoder finds the key that field reads, port. The error now stands on 70000 at line 6.

Variations

  • go-playground/validator. Its ValidationErrors already has this shape. Pass its Struct method: codec.Validator(validator.New().Struct).
  • A stream. The option works the same on codec.NewDecoder. See A stream of documents.

The error kinds in full: Errors.