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

Routing

Real HTTP servers host many different endpoints, and often, these endpoints include dynamic parameters in the URL path.

For example, if you visit a GitHub repository at https://github.com/torvalds/linux, GitHub doesn’t have a static file for that exact path. Instead, they have a route matching /github.com/{username}/{repo} and they extract torvalds and linux from the URL dynamically!

Your Task

Set up a dynamic route: /echo/{string}.

When a client sends a GET request to /echo/something, you must extract the something part of the path, and return it to the client.

Since you haven’t learned how to send Response Bodies yet, you will return the extracted string inside a custom response header called X-Echo.

Example Request: GET /echo/hello_world HTTP/1.1

Example Expected Response:

HTTP/1.1 200 OK\r\n
X-Echo: hello_world\r\n
\r\n

Tip

You can check if the request path starts with /echo/ and then extract the substring that follows it to get the dynamic parameter! Most languages provide string methods like startsWith, substring, split, or slicing to make this easy. Just be sure to handle the case where the client requests a different path (continue returning 404 Not Found for unknown paths).


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 routing