jokecode
rich / zit Private

Tiny git server in Zig — smart-http v2, stores objects in R2

ziggitserverwasm
zit / src / main.zig
32 lines · 1.1 KB · zig
const std = @import("std");
const protocol = @import("protocol.zig");
const refs = @import("refs.zig");

/// Entry point — Cloudflare Worker calls this for every HTTP request.
pub export fn handle(req_ptr: [*]const u8, req_len: usize) callconv(.C) usize {
    const allocator = std.heap.wasm_allocator;
    const body = req_ptr[0..req_len];

    const route = parseRoute(body) catch return errorResponse(500);

    return switch (route) {
        .info_refs => protocol.advertiseRefs(allocator),
        .upload_pack => protocol.uploadPack(allocator, body),
        .receive_pack => protocol.receivePack(allocator, body),
        .unknown => errorResponse(404),
    };
}

const Route = enum { info_refs, upload_pack, receive_pack, unknown };

fn parseRoute(body: []const u8) !Route {
    if (std.mem.indexOf(u8, body, "/info/refs") != null) return .info_refs;
    if (std.mem.indexOf(u8, body, "/git-upload-pack") != null) return .upload_pack;
    if (std.mem.indexOf(u8, body, "/git-receive-pack") != null) return .receive_pack;
    return .unknown;
}

fn errorResponse(_: u16) usize {
    return 0; // TODO: encode HTTP error frame
}