build-an-http-server / lesson-09.md
Lesson 09 · Parsing requests

Collect headers into a map

A request usually carries several headers, so today you parse each line of the header block and gather them into a lookup by name, the structure handlers will read from.

The goal

Parse every header line in the head into a map from name to value.

Start here - the target
TO DO
Scenario: Building the header map
Giventhe header lines "Host: example.com" and "Accept: */*"
Whenthey are collected and looked up by name
Thenlooking up "Host" gives "example.com" and "Accept" gives "*/*"
Andlooking up a name that was not sent gives the empty string
Background

With one header line parsed, the whole block is a loop: run every line after the request line through parseHeader and store the results in a Headers map with a Get accessor. That Get is how the rest of the server asks questions like “what is the Content-Length?” or “which Host was requested?” — and an absent header simply reads back as empty.

Keep the request line out of this — it was already parsed separately. You are folding just the header lines from the head into a name-to-value map, one entry per field.

Make it work
type Headers map[string]string
func (h Headers) Get(name string) string { return h[name] } // exact match, for now
// build it by running each header line through parseHeader and storing the result
CheckpointDONE
A request's headers collect into a lookup, with absent names reading empty. Commit.