ownmedia/src/main.zig
Alan Daniels 50117ff78d init
2025-11-02 12:54:03 +11:00

121 lines
3.3 KiB
Zig

//!
//! Part of the Zap examples.
//!
//! Build me with `zig build app_basic`.
//! Run me with `zig build run-app_basic`.
//!
const std = @import("std");
const Allocator = std.mem.Allocator;
const builtin = @import("builtin");
const optimize_mode = builtin.mode;
const zap = @import("zap");
const sqlite = @import("sqlite");
// The global Application Context
const Context = @import("Context");
// A very simple endpoint handling only GET requests
const SimpleEndpoint = struct {
// zap.App.Endpoint Interface part
path: []const u8,
error_strategy: zap.Endpoint.ErrorStrategy = .log_to_response,
// data specific for this endpoint
component: []const u8,
pub fn init(path: []const u8, data: []const u8) SimpleEndpoint {
return .{
.path = path,
.component = data,
};
}
// handle GET requests
pub fn get(e: *SimpleEndpoint, arena: Allocator, context: *Context, r: zap.Request) !void {
const thread_id = std.Thread.getCurrentId();
try Context.SendInertiaResponse(e, r, arena, e.component, .{
.thread_id = thread_id,
.counter = context.counter,
});
context.*.counter += 1;
}
};
const StopEndpoint = struct {
path: []const u8,
error_strategy: zap.Endpoint.ErrorStrategy = .log_to_response,
pub fn get(_: *StopEndpoint, _: Allocator, context: *Context, _: zap.Request) !void {
std.debug.print(
\\Before I stop, let me dump the app context:
\\db_connection='{}'
\\
\\
, .{context.*.db_connection});
zap.stop();
}
};
pub fn main() !void {
// setup allocations
var gpa: std.heap.GeneralPurposeAllocator(.{
// just to be explicit
.thread_safe = true,
}) = .{};
defer std.debug.print("\n\nLeaks detected: {}\n\n", .{gpa.deinit() != .ok});
const allocator = gpa.allocator();
var db = try sqlite.Db.init(.{
.mode = sqlite.Db.Mode{ .File = "./storage/mydata.db" },
.open_flags = .{
.write = true,
.create = true,
},
.threading_mode = .MultiThread,
});
defer db.deinit();
// create an app context
var my_context = Context.init(db);
// create an App instance
// const App = zap.App.Create(Context);
const App = @import("./App.zig").Create(Context);
try App.init(allocator, &my_context, .{});
defer App.deinit();
// create the endpoints
var home_endpoint = SimpleEndpoint.init("/", "home/home");
var test_endpoint = SimpleEndpoint.init("/test", "home/test");
var stop_endpoint: StopEndpoint = .{ .path = "/stop" };
// register the endpoints with the App
try App.register(&stop_endpoint);
try App.register(&home_endpoint);
try App.register(&test_endpoint);
// listen on the network
try App.listen(.{
.interface = "0.0.0.0",
.port = 3000,
.public_folder = "./public",
});
std.debug.print("Listening on 0.0.0.0:3000\n", .{});
std.debug.print(
\\ Try me via:
\\ curl http://localhost:3000/test
\\ Stop me via:
\\ curl http://localhost:3000/stop
\\
, .{});
// start worker threads -- only 1 process!!!
zap.start(.{
.threads = 2,
.workers = 1,
});
}