typescript 50 lines · 8 steps

Parsing HTTP Content-Range headers in TypeScript

Validate and destructure a Content-Range header with a named-group regex, then compute the next range to request.

Explained by highlit
1interface ContentRange {
2 unit: string;
3 start: number;
4 end: number;
5 total: number | null;
6 receivedLength: number;
7 isComplete: boolean;
8}
9 
10const CONTENT_RANGE = /^(?<unit>[\w-]+)\s+(?:(?<start>\d+)-(?<end>\d+)|\*)\/(?<total>\d+|\*)$/;
11 
12export function parseContentRange(header: string): ContentRange {
13 const match = CONTENT_RANGE.exec(header.trim());
14 if (!match?.groups) {
15 throw new Error(`Malformed Content-Range header: "${header}"`);
16 }
17 
18 const { unit, start, end, total } = match.groups;
19 
20 if (start === undefined || end === undefined) {
21 throw new Error(`Unsatisfied range in Content-Range: "${header}"`);
22 }
23 
24 const startByte = Number(start);
25 const endByte = Number(end);
26 
27 if (endByte < startByte) {
28 throw new Error(`Invalid range: end ${endByte} precedes start ${startByte}`);
29 }
30 
31 const totalBytes = total === "*" ? null : Number(total);
32 
33 if (totalBytes !== null && endByte >= totalBytes) {
34 throw new Error(`Range end ${endByte} exceeds total ${totalBytes}`);
35 }
36 
37 return {
38 unit,
39 start: startByte,
40 end: endByte,
41 total: totalBytes,
42 receivedLength: endByte - startByte + 1,
43 isComplete: totalBytes !== null && endByte === totalBytes - 1,
44 };
45}
46 
47export function nextRangeHeader(range: ContentRange): string | null {
48 if (range.isComplete || range.total === null) return null;
49 return `${range.unit}=${range.end + 1}-`;
50}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Named capture groups let a single regex both validate structure and label the values you extract.
  2. 2Validate each assumption with a specific error message so malformed input fails loudly instead of silently.
  3. 3Deriving fields like receivedLength and isComplete at parse time keeps downstream logic simple and trustworthy.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Parsing HTTP Content-Range headers in TypeScript — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code