Get the latest tech news

How do HTTP servers figure out Content-Length?


Anyone who has implemented a simple HTTP server can tell you that it is a really simple protocol. Basically, it’s a text file that has some specific rules to make parsing it easier. All HTTP requests look something like this: 1 GET /path HTTP/1.1\r\n Host: aarol.dev\r\n Accept-Language: en,fi-FI\r\n Accept-Encoding: gzip, deflate\r\n \r\n The first line is the “request line”, and it has the requested method, path and HTTP version. The following lines are headers, each terminated with “carriage return” and “line feed” characters. There is also an extra CRLF at the end, to mark the end of the header section. After that, there is the message body which can whatever data you want to send.

Our message is being chunked, sent in multiple parts, so that the server doesn’t need to fit the whole thing into memory at once. Behind this API is a lot of magic, including Content-Type sniffing and the implicit header writing I mentioned above. It’s great that these things are handled automatically, but in programming I think it’s always important to have an idea of what is happening at the layer below.

Get the Android app

Or read this on Hacker News

Read more on:

Photo of HTTP servers

HTTP servers

Photo of Content-Length

Content-Length