Parse an HTTP request

An HTTP request is plain text. Take it apart the way a web server does.

What to build

A program that reads a request and prints its method, path, query parameters and Host header.

Requirements

  • Print method M and path P (the target without its query).
  • Print one line param key=value for every query parameter, sorted by key (if a key repeats, the last value wins).
  • Print host H from the Host header (any capital letters in the name), or host none when there is none, then headers N with the number of header lines.

Input

The lines of the request: the request line, then header lines, then an empty line.

Output

The lines described above.

Constraints

At most 20 headers; no body.

Example

Input:

GET /search?q=network&page=2 HTTP/1.1
Host: example.com
Accept: text/html

Output:

method GET
path /search
param page=2
param q=network
host example.com
headers 2

Why it works

The request line gives method, target and version. The target splits at the question mark into path and query, and the query is a list of key=value pairs. Headers come after the first line until the blank line.

Examples

Example 1 · Input
GET /search?q=network&page=2 HTTP/1.1
Host: example.com
Accept: text/html
Expected output
method GET
path /search
param page=2
param q=network
host example.com
headers 2
Example 2 · Input
GET /about.html HTTP/1.1
Host: example.com
Expected output
method GET
path /about.html
host example.com
headers 1

Prompts inside input() are ignored when checking, so input("n: ") is fine.

Hints

Hint 1

Read lines with input() until you get an empty line. The first line is the request line.

Hint 2

Split the target at the first "?". The query is split at "&", and each part at the first "=" (a part without "=" has an empty value).

Hint 3

Header names are not case sensitive: compare name.lower() with "host".

Solution

Show one correct solution (try it yourself first)
lines = []
while True:
    try:
        line = input()
    except EOFError:
        break
    if line.strip() == "":
        break
    lines.append(line)
method, target, version = lines[0].split(" ")
path, _, query = target.partition("?")
params = {}
if query:
    for part in query.split("&"):
        key, _, value = part.partition("=")
        params[key] = value
host = "none"
for line in lines[1:]:
    name, _, value = line.partition(":")
    if name.strip().lower() == "host":
        host = value.strip()
print("method", method)
print("path", path)
for key in sorted(params):
    print("param " + key + "=" + params[key])
print("host", host)
print("headers", len(lines) - 1)

▶ Open this solution in the compiler, then press Visualize to watch it run step by step

Lesson: DNS and HTTP: the application layer →