📖 3 min read (~ 500 words).

A stream of documents

The task: read a file of jobs separated by ---, one Job per document, and keep the good ones when one document is wrong.

The type and the stream

type Job struct {
	Name  string `yaml:"name"`
	Every string `yaml:"every"`
}

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

// The second document writes a sequence where Job.Every is a string.
const jobs = `name: backup
every: 1h
---
name: report
every: [1d]
---
name: purge
every: 7d
`

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

The loop

// stops reports an error after which the decoder reads nothing more of the stream.
func stops(err error) bool {
	return errors.Is(err, yerrors.ErrSyntax) || errors.Is(err, yerrors.ErrExceededMaxDepth)
}

// readJobs decodes one Job per document, and goes on past a document that fails.
func readJobs(w io.Writer, r io.Reader) {
	dec := codec.NewDecoder(r)
	for i := 0; ; i++ {
		var j Job
		err := dec.Decode(&j)
		switch {
		case errors.Is(err, io.EOF):
			return
		case err != nil && stops(err):
			fmt.Fprintf(w, "document %d: stream stops: %v\n", i, firstLine(err))

			return
		case err != nil:
			fmt.Fprintf(w, "document %d: %v, kept %+v\n", i, firstLine(err), j)
		default:
			fmt.Fprintf(w, "document %d: %+v\n", i, j)
		}
	}
}

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

Decoder.Decode reads the next document into the value it is given, and returns io.EOF once the stream holds no more. Decode each document into a fresh value: a value reused across calls keeps the fields the next document leaves out.

A document that fails

readJobs(os.Stdout, strings.NewReader(jobs))
readJobs(os.Stdout, strings.NewReader(broken))

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

document 0: {Name:backup Every:1h}
document 1: [5:8] cannot unmarshal []interface {} into Go struct field Job.Every of type string, kept {Name:report Every:}
document 2: {Name:purge Every:7d}

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

A value that does not fit its field leaves that field alone. Decode reads the rest of the document, fills Name, and returns the error. The next call reads the next document.

A document that cannot be parsed

// The second document opens a flow sequence and never closes it.
const broken = `name: backup
every: 1h
---
name: [report
---
name: purge
every: 7d
`

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

readJobs(os.Stdout, strings.NewReader(broken))

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

document 0: {Name:backup Every:1h}
document 1: stream stops: [5:1] a flow collection continues on a line that is not indented past the one it started on

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

A syntax error stops the stream: the parser cannot tell where the broken document ends, so purge is never read. Every later call returns the same error, never io.EOF, which is why the loop tests errors.ErrSyntax and errors.ErrExceededMaxDepth and returns.

Variations

  • A repeated key fails its own Decode with errors.ErrDuplicateKey, and the next call reads the next document. The mapping holding the repeat is decoded in full first, with the later value. See Errors.
  • Anchors do not cross a ---: an alias in one document cannot name an anchor declared in another.
  • One document only. codec.Unmarshal decodes the first document of a stream and still reads the others, returning an error if one cannot be parsed.

The decoder’s entry points: Marshal and Unmarshal.