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:
- Combine your chosen base directory with the
{filename}from the URL. - Open the file on disk.
- If the file exists, return a
200 OKresponse with:
Content-Type: application/octet-streamContent-Lengthset to the size of the file.- The file contents as the Response Body.
- If the file does NOT exist, return a
404 Not Foundresponse.
Note
application/octet-streamis the standard MIME type for an arbitrary binary file.
Important
Run the below docker command to test your solution. Note the
-vflag: you must replace<YOUR_DIRECTORY>with the absolute path to the directory your server is serving from!This mounts your host directory to
/file_servinginside the container. The tester is hardcoded to create and request test files from this specific/file_servingpath!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