📖 4 min read (~ 700 words).

A type that decodes itself

The task: a configuration writes sizes as 10MiB and webhooks as URLs. Decode both into Go types that hold them properly.

A type of your own

// Size is a byte count written with a unit: "512KiB", "10MiB".
type Size int64

var errSize = errors.New("invalid size")

// UnmarshalYAML receives the YAML text of the value, as the document wrote it.
func (s *Size) UnmarshalYAML(text []byte) error {
	// Decode the text as a string first: this strips the quotes of "10MiB"
	// and rejects a mapping or a sequence.
	var str string
	if err := codec.Unmarshal(text, &str); err != nil {
		return err
	}

	units := []struct {
		suffix string
		scale  int64
	}{{"GiB", 1 << 30}, {"MiB", 1 << 20}, {"KiB", 1 << 10}, {"B", 1}}
	for _, u := range units {
		if digits, ok := strings.CutSuffix(str, u.suffix); ok {
			n, err := strconv.ParseInt(digits, 10, 64)
			if err != nil {
				return fmt.Errorf("%w: %q", errSize, str)
			}
			*s = Size(n * u.scale)

			return nil
		}
	}

	return fmt.Errorf("%w: %q has no unit", errSize, str)
}

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

A type with an UnmarshalYAML([]byte) error method implements codec.Unmarshaler, and the decoder calls it with the value’s YAML text, as the document wrote it. A quoted scalar arrives with its quotes, and a sequence arrives as [1, 2]. Decoding the text into a string with codec.Unmarshal strips the quotes, and returns an error for a mapping or a sequence.

type Limits struct {
	Upload Size `yaml:"upload"`
	Cache  Size `yaml:"cache"`
}

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

var l Limits
err := codec.Unmarshal([]byte("upload: 10MiB\ncache: \"512KiB\"\n"), &l)
fmt.Printf("%+v %v\n", l, err)

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

{Upload:10485760 Cache:524288} <nil>

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

When it fails

var l Limits
err := codec.Unmarshal([]byte("upload: 10\ncache: 1KiB\n"), &l)
fmt.Println(err)
fmt.Println(errors.Is(err, errSize))
fmt.Printf("%+v\n", l)

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

[1:9] invalid size: "10" has no unit
>  1 | upload: 10
               ^
   2 | cache: 1KiB
true
{Upload:0 Cache:1024}

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

The decoder wraps the method’s error in errors.ErrUnmarshaler at the value the method was decoding, so it prints the line and column and the source around them. errors.Is still reaches errSize. The decode goes on, so Cache is filled.

A type you do not own

url.URL has no YAML method, and the decoder reads it as a struct:

type Webhook struct {
	Target url.URL `yaml:"target"`
}

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

var w Webhook
err := codec.Unmarshal([]byte(src), &w)
fmt.Println(err)

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

Give the decode a function for the type with codec.CustomUnmarshaler. It receives the same YAML text a method would:

// parseURL decodes a url.URL from its YAML text.
func parseURL(u *url.URL, text []byte) error {
	var str string
	if err := codec.Unmarshal(text, &str); err != nil {
		return err
	}
	parsed, err := url.Parse(str)
	if err != nil {
		return err
	}
	*u = *parsed

	return nil
}

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

var c Webhook
err = codec.Unmarshal([]byte(src), &c, codec.CustomUnmarshaler(parseURL))
fmt.Println(c.Target.Host, c.Target.Query().Get("token"), err)

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

[1:9] string was used where mapping is expected
>  1 | target: https://hooks.example.com/build?token=abc
               ^

hooks.example.com abc <nil>

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

For every decode

codec.RegisterCustomUnmarshaler installs the function for every decoder in the process:

codec.RegisterCustomUnmarshaler(func(a *mail.Address, text []byte) error {
	var str string
	if err := codec.Unmarshal(text, &str); err != nil {
		return err
	}
	parsed, err := mail.ParseAddress(str)
	if err != nil {
		return err
	}
	*a = *parsed

	return nil
})

var team struct {
	Owner mail.Address `yaml:"owner"`
}
err := codec.Unmarshal([]byte("owner: Ada Lovelace <ada@example.com>\n"), &team)
fmt.Printf("%q %q %v\n", team.Owner.Name, team.Owner.Address, err)

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

"Ada Lovelace" "ada@example.com" <nil>

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

A registration is global. Two packages that register a function for one type replace each other’s, and neither sees it. Prefer CustomUnmarshaler, which applies to one call and takes precedence over a registered function.

Variations

  • The node, not the text. codec.NodeUnmarshaler receives the ast.Node the value was read from, with its position and comments.
  • The go-yaml v2 shape. codec.GoYAMLUnmarshaler, UnmarshalYAML(func(any) error) error, decodes the value into a destination of your choice.

The interfaces in full: Marshal and Unmarshal.