@@ -63,19 +63,34 @@ exe.root_module.addImport("http2", http2_dep.module("http2"));
6363const std = @import("std");
6464const http2 = @import("http2");
6565
66+ fn indexHandler(ctx: *const http2.Context) !http2.Response {
67+ return ctx.response.text(.ok, "hello from http2.zig\n");
68+ }
69+
70+ fn notFoundHandler(ctx: *const http2.Context) !http2.Response {
71+ return ctx.response.text(.not_found, "not found\n");
72+ }
73+
6674pub fn main() !void {
67- var gpa = std.heap.GeneralPurposeAllocator (.{}){} ;
75+ var gpa: std.heap.DebugAllocator (.{}) = .init ;
6876 defer _ = gpa.deinit();
6977 const allocator = gpa.allocator();
7078
7179 // Initialize the HTTP/2 system
7280 try http2.init(allocator);
7381 defer http2.deinit();
7482
83+ // Configure the request router
84+ var router = http2.Router.init(allocator);
85+ defer router.deinit();
86+
87+ try router.get("/", indexHandler);
88+ router.setFallback(notFoundHandler);
89+
7590 // Configure and create server
7691 const config = http2.Server.Config{
77- .address = try std.net.Address.resolveIp ("127.0.0.1", 3000),
78- .max_connections = 1000 ,
92+ .address = try std.Io. net.IpAddress.parse ("127.0.0.1", 3000),
93+ .router = &router ,
7994 };
8095
8196 var server = try http2.Server.init(allocator, config);
99114``` zig
100115pub const Server.Config = struct {
101116 /// Address to bind to
102- address: std.net.Address,
117+ address: std.Io.net.IpAddress,
118+
119+ /// Request router for handling HTTP requests
120+ router: *Router,
103121
104122 /// Maximum concurrent connections (default: 1000)
105123 max_connections: u32 = 1000,
@@ -109,6 +127,35 @@ pub const Server.Config = struct {
109127};
110128```
111129
130+ ### Router
131+
132+ The server expects a router in ` Server.Config ` , and requests are dispatched through it.
133+
134+ ``` zig
135+ try router.get("/", indexHandler);
136+ try router.post("/api/messages", createMessageHandler);
137+ try router.getPrefix("/assets", staticAssetsHandler);
138+ router.setFallback(notFoundHandler);
139+ ```
140+
141+ Current routing behavior:
142+
143+ - ` get ` , ` post ` , ` put ` , ` delete ` , ` head ` , ` options ` , and ` patch ` register exact routes.
144+ - ` getPrefix ` and ` postPrefix ` register prefix routes.
145+ - Prefix routes are ordered by longest path first.
146+ - Prefix matching is segment-aware: ` /api ` matches ` /api ` and ` /api/users ` , but not ` /apix ` .
147+ - A matching path with the wrong method returns ` 405 Method Not Allowed ` .
148+ - A missing path falls through to the fallback handler when configured; otherwise it returns ` 404 Not Found ` .
149+
150+ The request context passed to handlers exposes:
151+
152+ - ` ctx.method `
153+ - ` ctx.path `
154+ - ` ctx.query `
155+ - ` ctx.headers `
156+ - ` ctx.body `
157+ - ` ctx.response `
158+
112159### Server Methods
113160
114161``` zig
0 commit comments