Skip to content

Instantly share code, notes, and snippets.

@DutchGhost
Last active July 1, 2023 22:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DutchGhost/20566cb2b6c72073ea463d5ef16f8cd5 to your computer and use it in GitHub Desktop.
Save DutchGhost/20566cb2b6c72073ea463d5ef16f8cd5 to your computer and use it in GitHub Desktop.
funky compime zig
const std = @import("std");
// Just a simple struct representing a http route
// you can image this having a handler: fn() HttpResponse
// of some kind.
const Route = struct {
url: []const u8,
};
// a router namespace
const router = blk: {
// the list of registered routes
var routes: []const Route = &.{};
break :blk struct {
// converts a string into a route
pub fn route(path: []const u8) Route {
return Route { .url = path };
}
// registers a route to the routelist
pub fn add(comptime path: Route) void {
routes = routes ++ .{ path };
}
pub fn print_all() void {
for(routes) |r| {
@compileLog(r);
}
}
pub fn print() anyerror!void {
const stdout = std.io.getStdOut().writer();
for(routes) |r| {
try stdout.print("route {}!\n", .{r});
}
}
};
};
comptime {
router.add(router.route("hello"));
router.add(router.route("world"));
router.add(router.route("what is up"));
}
pub fn main() anyerror!void {
try router.print();
}
const std = @import("std");
// Just a simple struct representing a http route
// you can image this having a handler: fn() HttpResponse
// of some kind.
const Route = struct {
url: []const u8,
};
fn makeRouter(comptime _: anytype) type {
// a router namespace
const rrouter = blk: {
comptime var routes: []const Route = &.{};
break :blk struct {
// the list of registered routes
// converts a string into a route
pub fn route(path: []const u8) Route {
return Route { .url = path };
}
// registers a route to the routelist
pub fn add(comptime path: Route) void {
routes = routes ++ .{ path };
}
pub fn print_all() void {
for(@This().routes) |r| {
@compileLog(r);
}
}
pub fn print() anyerror!void {
const stdout = std.io.getStdOut().writer();
for(routes) |r| {
try stdout.print("route {s}!\n", .{r.url});
}
}
};
};
return rrouter;
}
const router = makeRouter(.{});
const router2 = makeRouter(.{});
comptime {
router.add(router.route("hello"));
router.add(router.route("world"));
router.add(router.route("what is up"));
router2.add(router2.route("Im router2"));
}
pub fn main() anyerror!void {
comptime {
router.add(router.route("main"));
}
try router.print();
try router2.print();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment