Skip to content

Commit

Permalink
on_request fallback for SimpleHttpListener
Browse files Browse the repository at this point in the history
  • Loading branch information
renerocksai committed May 16, 2023
1 parent a19acae commit 8067c66
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 3 deletions.
2 changes: 1 addition & 1 deletion build.zig.zon
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
.{
.name = "zap",
.version = "0.0.19",
.version = "0.0.20",

.dependencies = .{
.@"facil.io" = .{
Expand Down
11 changes: 10 additions & 1 deletion examples/endpoint/main.zig
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,15 @@ const std = @import("std");
const zap = @import("zap");
const Endpoint = @import("endpoint.zig");

// this is just to demo that we can catch arbitrary slugs
fn on_request(r: zap.SimpleRequest) void {
if (r.path) |the_path| {
std.debug.print("REQUESTED PATH: {s}\n", .{the_path});
}

r.sendBody("<html><body><h1>Hello from ZAP!!!</h1></body></html>") catch return;
}

pub fn main() !void {
var gpa = std.heap.GeneralPurposeAllocator(.{
.thread_safe = true,
Expand All @@ -13,7 +22,7 @@ pub fn main() !void {
allocator,
.{
.port = 3000,
.on_request = null,
.on_request = on_request,
.log = true,
.public_folder = "examples/endpoint/html",
.max_clients = 100000,
Expand Down
6 changes: 5 additions & 1 deletion src/endpoint.zig
Original file line number Diff line number Diff line change
Expand Up @@ -178,13 +178,14 @@ pub const SimpleEndpointListener = struct {

/// static struct member endpoints
var endpoints: std.ArrayList(*SimpleEndpoint) = undefined;
var on_request: ?zap.SimpleHttpRequestFn = null;

pub fn init(a: std.mem.Allocator, l: ListenerSettings) Self {
endpoints = std.ArrayList(*SimpleEndpoint).init(a);

var ls = l; // take copy of listener settings
ls.on_request = onRequest;

on_request = l.on_request;
return .{
.listener = Listener.init(ls),
.allocator = a,
Expand Down Expand Up @@ -227,5 +228,8 @@ pub const SimpleEndpointListener = struct {
}
}
}
if (on_request) |foo| {
foo(r);
}
}
};

0 comments on commit 8067c66

Please sign in to comment.