Deviopath › Node.js

HTTP Range Requests

Hard · HTTP

Video players and download managers ask for part of a file with the Range header, and the server answers 206 Partial Content. Implement handleRange(resource, headers) for single byte ranges, following RFC 9110.

resource is { body, etag }. body is a non-empty ASCII string (1 character = 1 byte, so the size is body.length). headers has lowercase keys and may contain range and if-range. Return { status, headers, body }. Every response has the header "Accept-Ranges": "bytes".

- No range header → 200 with the full body and "Content-Length" (as a string).

- If-Range (always an ETag here) is checked first: the range is only used if the value is exactly equal to resource.etag AND that ETag is strong (does not start with W/). Otherwise send the full 200. This stops a client from gluing together pieces of two different versions of a file.

- The header must be bytes=<first>-<last>, bytes=<first>- or bytes=-<suffix> (the unit bytes is case-insensitive, numbers are digits only). Anything else, first > last, or several ranges separated by commas → ignore the header and send the full 200 (RFC 9110 allows a server to ignore Range).

- first-last: last is clipped to size - 1. first-: from first to the end. -suffix: the last suffix bytes (the whole body if suffix >= size).

- The range is unsatisfiable when first >= size, or when it is a suffix range with suffix = 0 → 416 with "Content-Range": "bytes */<size>" and an empty body.

- Otherwise → 206 with the selected bytes, "Content-Range": "bytes <start>-<end>/<size>" and "Content-Length".

The driver runRange(resource, requests) is already written; it calls handleRange for each headers object.

Next: Worker Thread Pool Scheduler