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

Compression

Bandwidth is expensive, and plain text formats (like HTML, CSS, and JSON) are highly compressible. To make the web faster, HTTP supports Content Encoding.

When a client makes a request, they can include the Accept-Encoding header to tell the server which compression algorithms they understand (e.g., gzip, deflate, br).

If the server supports one of those algorithms, it can compress the Response Body, and add a Content-Encoding header to the response to tell the client how to decompress it!

Your Task

Create a new route: /compress/{string}.

  1. Read the Accept-Encoding header from the request.
  2. If it contains gzip (it might be a comma-separated list like gzip, deflate), you must:
  • Compress the {string} payload using the GZIP algorithm.
  • Add the header Content-Encoding: gzip.
  • Send the compressed bytes as the response body.
  • Set Content-Length to the size of the compressed payload.
  1. If Accept-Encoding does not contain gzip, or is missing entirely, respond exactly as you did in Send a Response Body (uncompressed plain text).

Note

You will need a GZIP library in your language to compress the string! (e.g. flate2 in Rust, zlib in Node.js/Python, compress/gzip in Go).


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 compression