Basic

Decoding into a shape

The bytes become a value, and the value has a type. The type is the check, and the check is the reason a wrong request never reaches the logic.

What you will see

One line with both lists. Both lists is what makes the error fixable.

About 1 min of reading

Try It

Refuse an unknown field

1

Write the expected shape

printf 'name\nversion\n' > /tmp/f.txt; wc -l < /tmp/f.txt

Before you run it, say out loud what it will print. Then open the answer.

What it prints
2. Two fields is the shape, and the shape is a file.
2

Send an extra field

printf 'name\nversion\ncolor\n' | comm -13 /tmp/f.txt -

Before you run it, say out loud what it will print. Then open the answer.

What it prints
color. The extra field is refused, and the name is what the client gets back.
3

Write the error back

printf '400 unknown field color allowed name,version\n' > /tmp/e.txt; cat /tmp/e.txt

Before you run it, say out loud what it will print. Then open the answer.

What it prints
One line with both lists. Both lists is what makes the error fixable.

Data Flow

Bytes to a typed value
1 The bytes are decoded
↓
2 Unknown fields are refused
↓
3 The value is typed
↓
4 A field error is named back
Why this works
Why the shape is written down

The shape is the contract of the route. A shape only in the code is a contract only the code knows.

The limit of a type

It checks form, not meaning. A number in range is still a number that can be wrong.

Examples

Strict beats lenient

An unknown field is an error. A silent ignore is a field that was meant to be read and was not.

Why the type is the whole validation

A field that is a string where a number is required fails at the decode. The logic never sees it.

The error is written back

The decode error names a field. The name is written to the client, and the client fixes it in one try.

Words this lesson uses

Each one is defined here on this site. Open the entry for the full definition and the other words it points at.

← Reading a body safely
Previous Lesson
Reading a body safely
Next Lesson
Shared state in a server
Shared state in a server →