⚡ Zig Guide LiveUnofficialbut fully verified
✓ Zig 0.18.0-dev.753+1420479beWhat's newOn an older Zig?Blograylib-zig

Web Server

HTTP is a text protocol. HTTP is simple enough to implement in an afternoon, and strict enough that the details are important. These chapters parse a request into a method, a target and headers. Then the chapters put a socket in front of the parser and answer a real client. The parser runs in this page. The server binds a port, so the server runs on the build machine, and CI checks what the client received.

  1. HTTP does not declare a length at the start, so a server reads until it finds a blank line. The blank-line rule is all of the framing.
  2. Header names are case-insensitive. An exact comparison works with your own client, and fails with a proxy that another person wrote.
  3. If a response has no Content-Length, the client continues to wait, because nothing else tells the client that the body ended.
  4. The parser never needs a socket. The parser takes bytes and returns a request. Thus you can test, fuzz and run the same code on a page that has no network.

8 chapters.

  • Parse an HTTP RequestA request line, some headers, a blank line. The blank line is the difficult part.
  • An HTTP ServerThe parser from the last chapter, with a socket in front of the parser.
  • Serve Files SafelyDecode first, then check. The opposite order is the bug.
  • Routes and Query StringsAll text after the question mark, and the dispatch table that ignores that text.
  • Form BodiesThe same encoding as a query string, but in the body, where it can be much larger.
  • Cookies and SessionsA cookie is a string that the client stores and sends back. All the rest is policy.
  • A Template EngineSubstitution is the easy half. Escaping by default is the more difficult half.
  • File UploadsA format where the client selects the delimiter, and a filename that you cannot trust until you check it.