Parse a Raw HTTP Request
Medium · HTTP
Before req.method and req.headers exist, Node's HTTP parser reads raw text like GET /x?y=1 HTTP/1.1\r\nHost: a\r\n\r\nbody. Write parseRequest(raw) that returns { method, path, query, version, headers, body }.
- The head and the body are separated by the FIRST \r\n\r\n. The body is everything after it (it may itself contain \r\n).
- The first line is METHOD target HTTP/x.y. version is the part after HTTP/, like "1.1" (the same as req.httpVersion).
- path is the target before ?. query is an object built from the part after ? with URLSearchParams (so + becomes a space and %26 becomes &; if a key repeats, the last value wins).
- Each header line is Name: value. Split at the FIRST :, lower-case the name, trim the value. If a header appears twice, join the values with ", " (Node does this for most headers).