Back
+30 XP
Concept

Gauntlet 02: Pure-Python HTTP 1.1 Web Server

Web frameworks like FastAPI and Flask abstract HTTP mechanics. A pure-Python HTTP 1.1 server handles raw socket byte streams directly, parsing method lines, extracting headers, routing request paths, and formatting compliant HTTP responses with CRLF delimiters.

python
# Raw HTTP/1.1 response framing:
# "HTTP/1.1 200 OK\r\nContent-Length: N\r\n\r\n{body}"
response = f"HTTP/1.1 {code} OK\r\nContent-Length: {len(body)}\r\n\r\n".encode() + body

# Gauntlet 02: Pure-Python HTTP 1.1 Web Server Every Python backend engineer uses web frameworks, but senior systems engineers understand the raw protocol on the wire. HTTP/1.1 (RFC 7230) is a plain-text request/response protocol running over TCP. 🌐⚡ A raw HTTP request looks like: ```text GET /api/v1/health HTTP/1.1\r\n Host: localhost:8080\r\n User-Agent: curl/7.88.1\r\n \r\n ``` A compliant HTTP/1.1 response must return: ```text HTTP/1.1 200 OK\r\n Content-Type: application/json\r\n Content-Length: 15\r\n \r\n {"status":"UP"} ``` In this gauntlet build, you will implement an HTTP/1.1 router that parses raw bytes, extracts method, path, and headers, dispatches to matching routes, and formats compliant response bytes. ```python # Delimited by double CRLF: headers_part, body_part = raw_bytes.split(b"\r\n\r\n", 1) ``` ## Pop Quiz Why must HTTP/1.1 headers strictly terminate each line with CRLF (`\r\n`) rather than standard Unix newlines (`\n`)? - [ ] The HTTP 1.1 RFC 7230 specification mandates CRLF delimiters for message boundaries and header line terminations. - [ ] Unix newlines cause Linux network cards to drop TCP checksum verification. - [ ] CRLF delimiters enable automatic gzip compression in web browser engines. - [ ] Because Python socket buffers ignore strings that end in a single line feed. ## Real-World Challenge Implement `MiniHTTPServer`: - `@route(method: str, path: str)` decorator to register endpoints. - `handle_raw_request(raw_bytes: bytes) -> bytes`: - Parses request line: `METHOD`, `PATH`, `VERSION`. - Routes to registered handlers: `fn(body: bytes) -> (status_code: int, headers: dict, body: bytes)`. - Returns `404 Not Found` if path is unmatched. - Automatically calculates and sets `Content-Length`. - Returns complete, compliant HTTP/1.1 response bytes. <details> <summary>Solution</summary> ```python class MiniHTTPServer: def __init__(self): self._routes = {} # (method, path) -> handler def route(self, method: str, path: str): def decorator(handler_fn): self._routes[(method.upper(), path)] = handler_fn return handler_fn return decorator def handle_raw_request(self, raw_bytes: bytes) -> bytes: parts = raw_bytes.split(b"\r\n\r\n", 1) header_text = parts[0].decode("iso-8859-1") body = parts[1] if len(parts) > 1 else b"" lines = header_text.split("\r\n") if not lines or not lines[0]: return b"HTTP/1.1 400 Bad Request\r\nContent-Length: 0\r\n\r\n" tokens = lines[0].split(" ") if len(tokens) < 2: return b"HTTP/1.1 400 Bad Request\r\nContent-Length: 0\r\n\r\n" method, path = tokens[0].upper(), tokens[1] handler = self._routes.get((method, path)) if not handler: return b"HTTP/1.1 404 Not Found\r\nContent-Length: 9\r\n\r\nNot Found" status_code, headers, resp_body = handler(body) status_text = "OK" if status_code == 200 else "Error" headers["Content-Length"] = str(len(resp_body)) header_lines = "".join(f"{k}: {v}\r\n" for k, v in headers.items()) head = f"HTTP/1.1 {status_code} {status_text}\r\n{header_lines}\r\n" return head.encode("iso-8859-1") + resp_body # Verification app = MiniHTTPServer() @app.route("GET", "/ping") def ping_handler(body): return 200, {"Content-Type": "text/plain"}, b"PONG" @app.route("POST", "/echo") def echo_handler(body): return 200, {"Content-Type": "application/octet-stream"}, body.upper() # 1. Test GET route get_req = b"GET /ping HTTP/1.1\r\nHost: localhost\r\n\r\n" res1 = app.handle_raw_request(get_req) assert b"HTTP/1.1 200 OK" in res1 assert b"Content-Length: 4" in res1 assert res1.endswith(b"PONG") # 2. Test POST route with body post_req = b"POST /echo HTTP/1.1\r\nHost: localhost\r\n\r\nhello server" res2 = app.handle_raw_request(post_req) assert res2.endswith(b"HELLO SERVER") # 3. Test 404 Not Found res3 = app.handle_raw_request(b"GET /missing HTTP/1.1\r\n\r\n") assert b"HTTP/1.1 404 Not Found" in res3 ``` </details>