Choose a request shape after resolving the URL
Fetch the example https://learn.example/lesson?q=cache using a fixed HTTP/1.1 message. Its request line is GET /lesson?q=cache HTTP/1.1 and its Host field identifies learn.example. A fragment is excluded. Method, request target, and version are distinct values. HTTPS encryption belongs to another layer that transports this message. Begin without network access: parsing a repeatable byte sequence makes it easier to isolate message-format mistakes from connection failures.
When constructing a request line, do not concatenate raw inputs containing line breaks. A newline could create an unintended field or an apparent second request. The fixed teaching client limits the method to GET and derives its target from the parsed URL. It also derives Host from parsed components rather than resplitting a display string. Log the interpreted address beside the constructed message and check three independent conditions: the query is retained, the fragment is excluded, and an empty line terminates the header section. These format tests need no external server. They establish what bytes the client intends to send before name resolution or a connection can introduce unrelated failure modes.
Establish the end of the header section first
In this HTTP/1.1 example, CRLF terminates lines and two consecutive CRLF sequences end the header section. Parse the status line, then header lines, then treat the remainder as candidate body bytes. A body may contain colons and line breaks, so splitting the entire message on colons is wrong. Header names are case-insensitive; their values follow field-specific rules. This teaching parser rejects unsupported framing combinations and duplicate Content-Length fields instead of attempting ambiguous recovery.
Content-Length counts bytes, not characters
The UTF-8 representation of the single character あ contains three bytes, so Content-Length: 3 describes those bytes. JavaScript string length is not a reliable substitute for an encoded body length. Retain incoming bytes in a byte-oriented buffer and decode the body with its character encoding once the required bytes are available. Track header boundaries as byte offsets too. A compressed representation introduces another distinction: the transferred representation and its expanded content need not have the same length.
Track the received byte count, header-end offset, required body length, and first unconsumed offset explicitly. If H is the byte position immediately after the header terminator and the body length is three, the message ends at H+3. Receiving H+2 bytes means one more byte is needed; H+5 leaves two bytes unconsumed. H is not merely the number of visible header characters. Bound header and body sizes instead of buffering forever. Even the teaching parser should distinguish waiting for more input from a size-limit failure. Tests can then prove that a small valid chunk does not fail while an oversized unfinished header does not wait without limit.
const body = new TextEncoder().encode('あ');
console.assert(body.byteLength === 3);
console.assert('あ'.length === 1);
const header = `HTTP/1.1 200 OK\r\nContent-Length: ${body.byteLength}\r\n\r\n`;
console.assert(header.endsWith('\r\n\r\n'));One read is not necessarily one message
A network read may end inside a header name or inside a multi-byte UTF-8 character. It may also contain bytes belonging to another message after the current body. Give the parser explicit states such as waiting for headers, waiting for body, and one message complete. Preserve unconsumed bytes. An ended stream with too few required body bytes is incomplete, not a successful short message. In the demonstration, vary the chunk boundaries while keeping the total message constant. The completed parsing result should remain unchanged.
A status code alone does not determine framing
Codes such as 200 and 404 describe response semantics but do not by themselves establish body length. Responses to HEAD and statuses such as 204 and 304 have special body rules. The first exercise deliberately supports a normal GET response with status 200 and one Content-Length. Expand support through separate tests for bodyless responses, chunked coding, and connection-close framing. Do not silently treat unsupported framing as an empty body: leftover bytes may then be misinterpreted as another response.
Message framing has ordered rules; finding a Content-Length field is not a universal instruction to use it. The teaching parser rejects unsupported forms to avoid presenting a narrow success as a complete HTTP implementation. Give it the supported request method and response status as explicit preconditions, and stop with an unsupported-format result if Transfer-Encoding appears. This does not label chunked coding invalid. When support expands, test accepted and rejected combinations, not only conversion of decimal length digits. A framing matrix makes missing cases visible. Correctly supporting one bounded form is a better foundation for the next lesson than partially accepting several forms with no consistent rule for their interaction.
Pass a defined result to document processing
Return status information, header fields, body bytes, and any unconsumed input. Before HTML parsing, another boundary checks content type and character encoding. An HTML error page with status 404 can still form a DOM; status 200 does not mean every body should be interpreted as HTML. Start with a fixed UTF-8 text/html response. Keep successful transfer separate from deciding how to display its content. Redirects and caching are later features built on correct message boundaries.
Exercise: combine two chunks and decide when to finish
After headers declare Content-Length: 5, body candidates arrive as AB and then CDE. The first chunk leaves the parser waiting; the second completes ABCDE. If the second chunk is CDEFG, the body remains ABCDE and FG stays unconsumed. Now split the three UTF-8 bytes of あ into one byte and two bytes. Decoding the completed body should still produce the same character. Report read count, byte length, and decoded character count separately. Reject truncation rather than treating missing data as a successful response.
A repeatable test splits one fixed message at every possible byte boundary, feeds the prefix, then feeds the suffix. That covers splits inside the status line, the header terminator, and the body without relying on unpredictable network timing. Every complete input should yield the same parsed body, and an insufficient prefix must not falsely report completion. Remove the final body byte and require an incomplete result even after the input ends. A real connection that happened to deliver everything at once cannot establish these properties. Also feed three chunks or one byte at a time through the same API. These tests exercise stored parsing state instead of merely checking a convenient whole-message parser.