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

File Serving

You have built an HTTP server capable of dynamic routing, concurrent processing, and chunked encoding! Now, let’s go back to the roots of the web: serving static files.

When a client requests an image, an HTML file, or a stylesheet, the server must read the file from the filesystem and return its contents in the Response Body.

Your Task

Because the tester runs inside a Docker container and your server runs on your host machine, they need a shared directory to test file serving. The tester will create a temporary file in this directory, and then ask your server to serve it!

Configure your server to serve files from a directory of your choice.

You must implement a new route: GET /files/{filename}.

When a client requests this endpoint, your server must:

  1. Combine your chosen base directory with the {filename} from the URL.
  2. Open the file on disk.
  3. If the file exists, return a 200 OK response with:
  • Content-Type: application/octet-stream
  • Content-Length set to the size of the file.
  • The file contents as the Response Body.
  1. If the file does NOT exist, return a 404 Not Found response.

Note

application/octet-stream is the standard MIME type for an arbitrary binary file.


Important

Run the below docker command to test your solution. Note the -v flag: you must replace <YOUR_DIRECTORY> with the absolute path to the directory your server is serving from!

This mounts your host directory to /file_serving inside the container. The tester is hardcoded to create and request test files from this specific /file_serving path!

docker run \
  --rm \
  -v <YOUR_DIRECTORY>:/file_serving \
  --add-host host.docker.internal:host-gateway \
  codeberg.org/level0/buildit/http-server:latest \
  --addr host.docker.internal:8080 \
  --until file_serving