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 meansUser-Agent,user-agent,USER-AGENT,uSeR-aGeNtare 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), meaningHost:localhostandHost: localhostare 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
/pingand the request contains the headerX-Test-Pingwith the exact valueping, respond with200 OK. - If the request target is
/pingand the header is missing, or has any other value, respond with400 Bad Request. - For other routes, maintain your existing logic (e.g.,
/returns200 OKregardless 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