← All languages

Servirtium for

Zig

No shipped package: vendor the binding's source at a release tag, with the native library from the release. Release v2.0.0-alpha.20.

FFI mechanism
link at build time (addLibraryPath + linkSystemLibrary). src/servirtium.zig is a single source file with the extern C ABI plus fluent Playback/Record builders returning a Server; the consumer's build.zig links libservirtium_vcr and bakes an rpath.
Toolchain
Zig 0.17.1 (build.zig.zon sets minimum_zig_version 0.17.0), libc linked; curl on PATH only for the upstream test suite.
Distribution
Vendor servirtium.zig from the tag + link the release native library in your build.zig
Finding the library
Linked at BUILD time: your build.zig adds the library directory with addLibraryPath, links 'servirtium_vcr' and bakes the same directory as an rpath. The package's own build.zig (tests only) reads SERVIRTIUM_VCR_LIB, otherwise ../core/native.
On GitHub
zig/ · README

Getting it

There is no published package for Zig. You vendor the binding's source into your project at the release tag v2.0.0-alpha.20 and take the native library from the same release.

  1. Fetch the native library for your OS/arch, verify its checksum, and give it the plain name the linker wants. Windows: take the .dll asset (and .dll.lib) by hand.
    TAG=v2.0.0-alpha.20
    REL=https://github.com/servirtium/servirtium-vcr/releases/download/$TAG
    case "$(uname -s)" in
      Linux)   OS=linux;   EXT=so;    ldd --version 2>&1 | grep -qi musl && LIBC=-musl || LIBC= ;;
      Darwin)  OS=macos;   EXT=dylib; LIBC= ;;
      FreeBSD) OS=freebsd; EXT=so;    LIBC= ;;
    esac
    case "$(uname -m)" in x86_64|amd64) ARCH=x86_64 ;; arm64|aarch64) ARCH=arm64 ;; esac
    LIBDIR="$HOME/.servirtium-vcr/$TAG"; mkdir -p "$LIBDIR"
    LIB=libservirtium_vcr-$TAG-$OS-$ARCH$LIBC.$EXT
    curl -fsSL -o "$LIBDIR/$LIB" "$REL/$LIB"
    curl -fsSL -o "$LIBDIR/$LIB.sha256" "$REL/$LIB.sha256"
    ( cd "$LIBDIR" && { sha256sum -c "$LIB.sha256" || shasum -a 256 -c "$LIB.sha256"; } )
    cp "$LIBDIR/$LIB" "$LIBDIR/libservirtium_vcr.$EXT"
    
  2. macOS only: the release .dylib carries a CI build path as its install name, so a binary linked against it aborts at start with 'Library not loaded: /home/runner/...'. Rewrite the install name and re-sign before building.
    install_name_tool -id @rpath/libservirtium_vcr.dylib "$LIBDIR/libservirtium_vcr.dylib"
    codesign -f -s - "$LIBDIR/libservirtium_vcr.dylib"
    
  3. Vendor the sources of the same tag. There is no registry package, and the package's build.zig only defines a test step (it exports no module), so you import the one source file by path rather than as a build.zig.zon dependency.
    git clone --depth 1 --branch v2.0.0-alpha.20 https://github.com/servirtium/servirtium-vcr.git third_party/servirtium-vcr
    
  4. In your build.zig, create the module from the vendored file, link the library and bake the rpath (this is the repository's zig/example/build.zig, with the paths changed).
    const servirtium = b.createModule(.{
        .root_source_file = b.path("third_party/servirtium-vcr/zig/src/servirtium.zig"),
    });
    const lib_dir = b.option([]const u8, "vcr-lib-dir", "directory holding libservirtium_vcr") orelse
        @panic("pass -Dvcr-lib-dir=<dir>");
    // exe_mod is your executable or test module, created with .link_libc = true
    exe_mod.addImport("servirtium", servirtium);
    exe_mod.addLibraryPath(.{ .cwd_relative = lib_dir });
    exe_mod.linkSystemLibrary("servirtium_vcr", .{});
    exe_mod.addRPath(.{ .cwd_relative = lib_dir });
    
  5. Build and run, pointing -Dvcr-lib-dir at the directory from step 1.
    zig build run -Dvcr-lib-dir="$LIBDIR"
    

Record

Point your client at the VCR's base URL; the VCR forwards to the real service and hands back the real response. Nothing is written until you commit.

const std = @import("std");
const servirtium = @import("servirtium");

pub fn main() !void {
    const a = std.heap.page_allocator;

    var rec = try servirtium.Record.init(a, "tapes/climate_api.md", "https://climatedataapi.worldbank.org")
        .port(0)
        .start();
    errdefer rec.discard();      // a failed test never leaves a half-recorded tape

    const base = try rec.baseUrl();
    defer a.free(base);
    // ... point your HTTP client at `base` and make requests ...

    try rec.commit();            // the only way a recording becomes a tape
}

Playback

The same tape, replayed with no network.

const std = @import("std");
const servirtium = @import("servirtium");

pub fn main() !void {
    const a = std.heap.page_allocator;

    var srv = try servirtium.Playback.init(a, "tapes/climate_api.md")
        .port(0)             // 0 picks a free port
        .start();
    defer srv.close() catch {};

    const base = try srv.baseUrl();
    defer a.free(base);
    // ... point your HTTP client at `base` and make requests ...

    if (srv.lastKind() != .ok) {
        const e = try srv.lastError();
        defer a.free(e);
        std.debug.print("mismatch: {s}\n", .{e});
    }
}

Idiomatic extras

Discard on error, close() on a recording is an error

close on a recording that was neither committed nor discarded returns error.VcrError and writes nothing.

var rec = try servirtium.Record.init(a, tape, upstream).port(0).start();
errdefer rec.discard();
// ... drive the SUT; any error above drops the recording ...
try rec.commit();

Redact credentials

The builder scrubs the standard credential headers while the live test still sees real bytes; redactHeader, redactQueryParam and redactJsonField cover named ones.

var rec = try servirtium.Record.init(a, tape, upstream)
    .redactCredentials()
    .redactJsonField("secretKey")
    .port(0)
    .start();

Volatile values (byte-identical re-records)

A bad rule fails start with error.VcrError; startDiagnosed(&diag) gives the core's message.

var rec = try servirtium.Record.init(a, tape, upstream)
    .volatileRule("response headers", "Date: {{serverDate}}")
    .volatileRuleKind("body", "(?<id>[0-9a-f]{32})", "regex")
    .failIfChanged()
    .start();

Gotchas

  • The README has no Getting-it section: these steps are derived from build.zig, build.zig.zon, zig/example/build.zig and .example.ae. build.zig.zon lists paths but build.zig exports no module, so a .dependencies entry is not enough.
  • Tape paths, hosts and patterns are NUL-terminated [:0]const u8 and borrowed: they must outlive start(). Returned strings are copied into your allocator; free them.
  • The builders use value semantics so Playback.init(...).port(0).start() chains; keep the result of start() in a var.
  • The library is linked, not dlopen-ed: use the same tag for source and library.

Prompt for your coding agent

Paste this into Claude, Codex, Gemini or any coding agent, in your Zig project. It wraps one of your existing integration tests with Servirtium. The general prompt has a slot for the language instead.

Hey Gemini or Claude or Codex,

I want a test in this Zig project to run without calling a real web service every time. Use Servirtium (https://servirtium.dev), which records HTTP conversations as readable Markdown "tapes" and replays them. Do these steps in order and tell me what you did at each one.

1. Find an existing integration test in this project that calls a web service as a side effect of what it is testing. Prefer one that is slow, flaky, or needs credentials or network because of that call. Tell me which test you chose and why.

2. Add the Servirtium binding for Zig. Follow https://servirtium.dev/languages/zig/ exactly. Servirtium ships no package for this language. Vendor the binding's source into the project at the release tag v2.0.0-alpha.20 and put the native library from the same release where the page says: Vendor servirtium.zig from the tag + link the release native library in your build.zig.
   Toolchain and minimum version: Zig 0.17.1 (build.zig.zon sets minimum_zig_version 0.17.0), libc linked; curl on PATH only for the upstream test suite..
   How the binding finds the native library: Linked at BUILD time: your build.zig adds the library directory with addLibraryPath, links 'servirtium_vcr' and bakes the same directory as an rpath. The package's own build.zig (tests only) reads SERVIRTIUM_VCR_LIB, otherwise ../core/native.

3. Route that test's HTTP client to the Servirtium VCR's base URL instead of the real service, using the idiomatic Zig way of setting a base URL or HTTP client. The VCR starts on its own port (use port 0, so it picks a free one) and gives you its base URL; give that URL to the client and never hard-code a port.

4. Run the test once in record mode against the real service. Commit the recording when the test passes and discard it when the test fails: a record VCR that is closed without a commit or a discard writes no tape and raises an error. Use redact_credentials (the spelling for Zig is on the page) so secrets become numbered tokens, and remove volatile request headers such as User-Agent and Date from the tape so playback does not depend on them.

5. Keep the tape beside the test as readable Markdown, in version control. Open it and check there are no secrets or personal data in it before committing.

6. Make the test play back by default, with an explicit switch (for example an environment variable such as SERVIRTIUM_RECORD=1) that re-records.

7. Prove it works offline: make the real service unreachable (network off, or a wrong host) and show the test still passes in playback.

Traps to avoid:
- A record VCR needs Commit() or Discard(); closing it without either writes nothing and raises.
- The VCR runs in your test process on its own port; the system under test must use the VCR's base URL, not the real one.
- The README has no Getting-it section: these steps are derived from build.zig, build.zig.zon, zig/example/build.zig and .example.ae. build.zig.zon lists paths but build.zig exports no module, so a .dependencies entry is not enough.
- Tape paths, hosts and patterns are NUL-terminated [:0]const u8 and borrowed: they must outlive start(). Returned strings are copied into your allocator; free them.
- The builders use value semantics so Playback.init(...).port(0).start() chains; keep the result of start() in a var.
- The library is linked, not dlopen-ed: use the same tag for source and library.

References:
- This language's page: https://servirtium.dev/languages/zig/
- The binding's directory: https://github.com/servirtium/servirtium-vcr/tree/main/zig
- Concepts, features and every language's quick start: https://servirtium.dev/llms-full.txt (index: https://servirtium.dev/llms.txt)

How these snippets were checked

Ran on macOS arm64 with Zig 0.17.1: release libservirtium_vcr-v2.0.0-alpha.20-macos-arm64.dylib (sha256 checked), a git clone of the tag vendored under third_party, and a consumer build.zig exactly as in step 4. Playback of single_get.md printed ok-body .ok; record against a local python http.server with redactCredentials and prettyJson, commit(), then replay printed hello-upstream .ok; close() on an uncommitted recording returned error.VcrError. The unmodified release dylib aborts at start (install name is a CI path); with install_name_tool -id @rpath/... and codesign it works. discard/errdefer, volatile and failIfChanged extras not run.

They mirror these files in the repository:

See also the feature reference, llms.txt and the zig/ directory.