Basic

A handler is a function

The handler takes the request and returns nothing. It writes the response, and writing rather than returning is what makes the errors a discipline.

What you will see

One line. Shared state is passed in, so the handler names what it was given.

About 1 min of reading

Try It

Split a handler into read and write

1

Write the read half

printf 'read body\nvalidate\n' > /tmp/h.txt; wc -l < /tmp/h.txt

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

What it prints
2. Two steps before anything is written, which is the shape.
2

Write the write half

printf 'status 200\nbody json\n' > /tmp/w.txt; head -1 /tmp/w.txt

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

What it prints
status 200. The status is the first byte written, always.
3

Name what is shared in

printf 'handler ping uses=config passed\n' > /tmp/s.txt; cat /tmp/s.txt

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

What it prints
One line. Shared state is passed in, so the handler names what it was given.

Data Flow

A request to a written response
1 The request body is read
↓
2 The input is validated
↓
3 The status and headers are written
↓
4 The body is written last
Why this works
Why the handler is written in halves

Read the input, then write the output. The split is where the error handling changes shape.

The testable form

A handler that takes a request and returns a response value. The server adapts it, and the test calls it directly.

Examples

There is no return value

The response is already half written when the error happens. A return value cannot undo the bytes already sent.

Headers before body

The status is written first. A status written after the body is a status that was already sent.

The handler owns no state

Anything shared is passed in. A handler that reaches a global is a handler that cannot be tested alone.

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.

← The server is in the standard library
Previous Lesson
The server is in the standard library
Next Lesson
Reading a body safely
Reading a body safely →