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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Named capture groups let a single regex both validate structure and label the values you extract.
- 2Validate each assumption with a specific error message so malformed input fails loudly instead of silently.
- 3Deriving fields like receivedLength and isComplete at parse time keeps downstream logic simple and trustworthy.
Related explainers
typescript
import { registerLocaleData } from '@angular/common'; import localeFr from '@angular/common/locales/fr'; import localeFrExtra from '@angular/common/locales/extra/fr'; import localeDe from '@angular/common/locales/de';
Locale-aware bootstrapping in Angular
i18n
localization
dependency-injection
Intermediate
8 steps
typescript
import { Module } from '@nestjs/common'; import { ConfigModule } from '@nestjs/config'; import * as Joi from 'joi';
Validating env config at boot in NestJS
configuration
schema-validation
environment-variables
Intermediate
8 steps
php
<?php namespace App\Services\Checkout;
Validating coupons with Laravel's Pipeline
pipeline
chain of responsibility
transactions
Intermediate
7 steps
ruby
class UserAgentParser BROWSERS = [ [/Edg\/([\d.]+)/, "Edge"], [/OPR\/([\d.]+)/, "Opera"],
Parsing user-agent strings in Ruby
regex
pattern-matching
lookup-tables
Intermediate
8 steps
javascript
function evaluate(expression) { const tokens = tokenize(expression); let pos = 0;
Building a recursive descent calculator
parsing
recursion
operator-precedence
Intermediate
8 steps
typescript
import { Inject, Injectable, Logger } from '@nestjs/common'; import { CACHE_MANAGER } from '@nestjs/cache-manager'; import { Cache } from 'cache-manager'; import { InjectRepository } from '@nestjs/typeorm';
A cache-aside country lookup in NestJS
cache-aside
dependency-injection
batch-lookup
Intermediate
8 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/parsing-http-content-range-headers-in-typescript-explained-typescript-0dd0/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.