lalinsky/dusty
HTTP server library for Zig
4bbbad90e830aab6d844746c701dc12e37217578Dusty is a simple HTTP server built on top of zio and llhttp. The API is very much inspired by Karl Seguin's http.zig, which is a great project and I would be happy using that, if I didn't need to run multiple network services inside the same application.
This project is in very early stages, don't use it unless you want to experiment or perhaps even contribute.
const std = @import("std");
const zio = @import("zio");
const http = @import("dusty");
const AppContext = struct {
rt: *zio.Runtime,
};
fn handleIndex(ctx: *AppContext, req: *http.Request, res: *http.Response) !void {
_ = ctx;
_ = req;
res.body = "Hello World!\n";
}
// ...
fn runServer(allocator: std.mem.Allocator, rt: *zio.Runtime) !void {
var ctx: AppContext = .{ .rt = rt };
var server = http.Server(AppContext).init(allocator, .{}, &ctx);
defer server.deinit();
server.router.get("/", handleIndex);
server.router.get("/file/:id", handleFile);
server.router.put("/upload/*path", handleUpload);
const addr = try zio.net.IpAddress.parseIp("127.0.0.1", 8080);
try server.listen(rt, addr);
}
pub fn main() !void {
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
defer _ = gpa.deinit();
const allocator = gpa.allocator();
var rt = try zio.Runtime.init(allocator, .{});
defer rt.deinit();
try rt.runUntilComplete(runServer, .{ allocator, rt }, .{});
}