Zero-Alloc HTTP Server

hard · systems, parsing, performance, allocation

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 GET is supported; any other method returns 405.
  • Paths:
    • GET / → 200, body hello
    • GET /health → 200, body ok
    • GET /echo?msg=... → 200, body is the raw msg value (no URL decoding)
    • Any other path → 404, body not found
  • If header X-Request-Id is present, echo it back as a response header.
  • If ctx is canceled, return ctx.Err() immediately.
  • If dst is too small, return ErrShortBuffer (and do not consume the request).
  • Malformed requests must return ErrBadRequest.
  • If the request is incomplete (no \r\n\r\n), return ErrNeedMore.
  • Return consumed as the byte index just after the header terminator (\r\n\r\n).
  • Support keep‑alive: if Connection: close is present, reply with Connection: close. Otherwise reply with Connection: 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

  • req may contain multiple requests (no bodies).
  • Header names are case‑insensitive.
  • Do not allocate on the hot path (tests enforce zero allocations).

Notes

  • Avoid converting []byte to string.
  • Compute content length without fmt.
Run tests to see results
No issues detected