Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Parse Request Headers

After the Request Line, an HTTP request contains zero or more Fields (colloquially known as Headers).

Headers are metadata key-value pairs that provide additional context about the request (e.g., what kind of device the client is using, what data formats they accept).

According to RFC 9112 Section 5, these fields are transmitted as a series of field lines following this grammar:

field-line   = field-name ":" OWS field-value OWS

Let’s break this down:

  • field-name: The name of the header (e.g., User-Agent). Header names are case-insensitive. It means User-Agent, user-agent, USER-AGENT, uSeR-aGeNt are all the same.
  • :: A literal colon character.
  • OWS: Optional Whitespace. This means there might be zero spaces, one space, or multiple spaces before or after the value!
  • field-value: The actual value of the header.

Example:

Host: localhost\r\n
user-agent:   curl/7.68.0  \r\n

Caution

A very common pitfall is assuming there is always exactly one space after the colon. The RFC says OWS (Optional Whitespace), meaning Host:localhost and Host: localhost are both perfectly valid and must be parsed identically. You must trim leading and trailing whitespace from the value!

Your Task

Create a new route: GET /ping.

When a client makes a request to this new endpoint, the tester will send requests containing a custom header: X-Test-Ping.

You must extract the value of this header for the /ping route only, taking care to handle case-insensitivity and whitespace trimming.

  • If the request target is /ping and the request contains the header X-Test-Ping with the exact value ping, respond with 200 OK.
  • If the request target is /ping and the header is missing, or has any other value, respond with 400 Bad Request.
  • For other routes, maintain your existing logic (e.g., / returns 200 OK regardless of headers).

Important

Run the below docker command to test your solution.

docker run \
  --rm \
  --add-host host.docker.internal:host-gateway \
  codeberg.org/level0/buildit/http-server:latest \
  --addr host.docker.internal:8080 \
  --until headers_parsing