Zero-Alloc HTTP Server
Zero‑Alloc HTTP Server
Implement a tiny HTTP/1.1 handler that parses a request and writes a response without allocating. The input buffer may contain multiple requests; handle only the first and return how many bytes you consumed so the caller can continue.
Function signature
func HandleRequest(ctx context.Context, req []byte, dst []byte) (consumed int, written int, err error)
Requirements
- Parse a single HTTP/1.1 request line and headers from
req. - Only
GETis supported; any other method returns 405. - Paths:
GET /→ 200, bodyhelloGET /health→ 200, bodyokGET /echo?msg=...→ 200, body is the rawmsgvalue (no URL decoding)- Any other path → 404, body
not found
- If header
X-Request-Idis present, echo it back as a response header. - If
ctxis canceled, returnctx.Err()immediately. - If
dstis too small, returnErrShortBuffer(and do not consume the request). - Malformed requests must return
ErrBadRequest. - If the request is incomplete (no
\r\n\r\n), returnErrNeedMore. - Return
consumedas the byte index just after the header terminator (\r\n\r\n). - Support keep‑alive: if
Connection: closeis present, reply withConnection: close. Otherwise reply withConnection: keep-alive.
Response format
HTTP/1.1 <status> <text>\r\n
Content-Length: <n>\r\n
Content-Type: text/plain; charset=utf-8\r\n
[X-Request-Id: <value>\r\n]
Connection: <close|keep-alive>\r\n
\r\n
<body>
Constraints
reqmay contain multiple requests (no bodies).- Header names are case‑insensitive.
- Do not allocate on the hot path (tests enforce zero allocations).
Notes
- Avoid converting
[]bytetostring. - Compute content length without
fmt.
Run tests to see results
No issues detected