1
0
Fork 0
mirror of https://github.com/zigzap/zap.git synced 2025-10-20 15:14:08 +00:00

dynamic route dispatch

This commit is contained in:
Rene Schallner 2023-01-12 19:49:07 +01:00
parent eaf501df30
commit 21daa0a16a
2 changed files with 62 additions and 1 deletions

View file

@ -19,7 +19,7 @@ pub fn build(b: *std.build.Builder) !void {
src: []const u8,
}{
.{ .name = "hello", .src = "examples/hello/hello.zig" },
// .{ .name = "routes", .src = "examples/routes/routes.zig" },
.{ .name = "routes", .src = "examples/routes/routes.zig" },
// .{ .name = "serve", .src = "examples/serve/serve.zig" },
}) |excfg| {
const ex_name = excfg.name;

View file

@ -0,0 +1,61 @@
const std = @import("std");
const zap = @import("zap");
fn dispatch_routes(r: zap.SimpleRequest) void {
// dispatch
if (r.path) |the_path| {
if (routes.get(the_path)) |foo| {
foo(r);
}
}
// or default: present menu
_ = r.sendBody(
\\ <html>
\\ <body>
\\ <p><a href="/static">static</a></p>
\\ <p><a href="/dynamic">dynamic</a></p>
\\ </body>
\\ </html>
);
}
fn static_site(r: zap.SimpleRequest) void {
_ = r.sendBody("<html><body><h1>Hello from STATIC ZAP!</h1></body></html>");
}
var dynamic_counter: i32 = 0;
fn dynamic_site(r: zap.SimpleRequest) void {
dynamic_counter += 1;
var buf: [128]u8 = undefined;
const filled_buf = std.fmt.bufPrintZ(
&buf,
"<html><body><h1>Hello # {d} from DYNAMIC ZAP!!!</h1></body></html>",
.{dynamic_counter},
) catch "ERROR";
_ = r.sendBody(std.mem.span(filled_buf));
}
fn setup_routes(a: std.mem.Allocator) !void {
routes = std.StringHashMap(zap.SimpleHttpRequestFn).init(a);
try routes.put("/static", static_site);
try routes.put("/dynamic", dynamic_site);
}
var routes: std.StringHashMap(zap.SimpleHttpRequestFn) = undefined;
pub fn main() !void {
try setup_routes(std.heap.page_allocator);
var listener = zap.SimpleHttpListener.init(.{
.port = 3000,
.on_request = dispatch_routes,
.log = true,
});
try listener.listen();
std.debug.print("Listening on 0.0.0.0:3000\n", .{});
zap.start(.{
.threads = 2,
.workers = 2,
});
}