Cookbook — copy-paste recipes
JSON API with tests
Section titled “JSON API with tests”import std.httpimport std.json
func handler(req: http.request) -> http.response { match http.body_json(req) { .ok(body) => http.ok(json.stringify(body) ?? "{}"), .err(e) => http.respond(400, "bad json: {e}"), }}
func routes() -> http.server { s := http.server() s = http.route(s, "POST", "/echo", handler) s}
func main() { http.listen(routes(), 8080)}import std.http
@testfunc test_echo() { res := http.test(routes(), "POST", "/echo", `{"a":1}`) assert_eq(res.status(), 200)}Static site with hardening
Section titled “Static site with hardening”import std.http
s := http.server()s = http.serve_dir_at(s, "/assets", "./dist")s = http.cors(s, ["https://app.example.com"])s = http.secure_headers(s)s = http.request_id(s)http.listen_cfg(s, 8080, {"max_body_bytes": 10000000})CLI with flags
Section titled “CLI with flags”import std.args
p := ArgsParser.new()p.str_flag("out", "out.txt")p.bool_flag("verbose")if p.parse(["--out", "a.txt"]) { println(p.get_str("out")) if p.get_bool("verbose") { println("verbose on") }} else { println(p.error())}CSV → JSON
Section titled “CSV → JSON”import std.csvimport std.jsonimport std.fs
func main() -> Result<int, str> { src := fs.read("data.csv")? rows := csv.parse(src) println(json.stringify(csv.to_json(rows)) ?? "[]") .ok(0)}Worker pool
Section titled “Worker pool”import std.taskimport std.chan
jobs := chan()out := chan()for i in 0..4 { task.spawn(|_| { while true { match chan.try_recv(jobs) { .some(j) => chan.send(out, j * 2), .none => break, } } })}for i in 0..100 { chan.send(jobs, i) }for i in 0..100 { v: int = chan.recv(out)}Full: examples/parallel_worker_pool.zz.
Hash a file (binary-safe)
Section titled “Hash a file (binary-safe)”import std.fsimport std.crypto
func main() -> Result<int, str> { b := fs.read_bytes("data.bin")? println(crypto.sha256_bytes(b)) .ok(0)}Regex extract
Section titled “Regex extract”import std.regexp
match regexp.compile(`[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}`) { .ok(re) => println(re.find("mail ada@example.com now") ?? "none"), .err(e) => println(e),}Demo: examples/regexp_email_demo/extract_emails.zz.
Env-gated server with graceful config
Section titled “Env-gated server with graceful config”import std.envimport std.http
func port() -> int { match env.get("PORT") { .some(p) => int(p) ?? 8080, .none => 8080, }}
func main() { s := http.server() s = http.route(s, "GET", "/health", |_req| "ok") s = http.log(s, true) http.listen(s, port())}SQLite users table with transaction
Section titled “SQLite users table with transaction”import std.sqlz
func main() -> Result<int, str> { db := sqlz.open("users.db") sqlz.exec(db, "CREATE TABLE IF NOT EXISTS users (id INTEGER, name TEXT)") n := sqlz.transaction(db, |tx| { sqlz.exec(tx, "INSERT INTO users VALUES (1, 'Ada')") sqlz.exec(tx, "INSERT INTO users VALUES (2, 'Bo')") 2 })? println("inserted {n}") rows := sqlz.query(db, "SELECT * FROM users") println(rows) sqlz.close(db) .ok(0)}Terminal picker with raw mode + colors
Section titled “Terminal picker with raw mode + colors”import std.termimport std.colors
func main() { if !term.is_tty() { println("needs a tty") return } match term.enable_raw() { .ok(_) => println("raw on"), .err(e) => println("no tty: {e}"), } defer term.disable_raw() match term.read_key() { .ok(k) => println("picked {k}" |> colors.green() |> colors.bold()), .err(e) => println(e), }}JWT issue + verify round-trip
Section titled “JWT issue + verify round-trip”import std.crypto
tok := crypto.jwt_encode("secret", `{"sub":"1"}`)match crypto.jwt_decode("secret", tok) { .ok(payload) => println("ok"), .err(e) => println("bad: {e}"),}Property test for a pure function
Section titled “Property test for a pure function”import std.property
func double(n: int) -> int { n * 2 }
func is_even_twice(x: int) -> bool { double(x) % 2 == 0}
property.for_all_int(-1000, 1000, is_even_twice, 200, 7)Rate-limited API with request IDs
Section titled “Rate-limited API with request IDs”import std.httpimport std.uuid
s := http.server()s = http.route(s, "GET", "/", |_req| "ok-{uuid.v7()}")s = http.rate_limit(s, 100, 60000)s = http.request_id(s)s = http.secure_headers(s)http.listen(s, 8080)Validated CSV ingest
Section titled “Validated CSV ingest”import std.csvimport std.fs
func main() -> Result<int, str> { src := fs.read("in.csv")? if csv.validate(src) { println("rows {csv.len(csv.parse(src))}") } else { println("bad csv") } println(csv.get_cell(csv.parse(src), 0, 0, "?")) .ok(0)}Process wrapper with env overlay
Section titled “Process wrapper with env overlay”import std.process
match process.run_with_env("make", ["test"], ["RUST_BACKTRACE=1"]) { .ok(out) => println("status {out[0]} out {out[1]}"), .err(e) => println("spawn failed: {e}"),}UUID-keyed ingest dedupe
Section titled “UUID-keyed ingest dedupe”import std.uuidimport std.set
ids := [uuid.v7(), uuid.v7()]ids = set.insert(ids, ids[0]) // duplicate ignoredprintln(set.len(ids)) // 2println(uuid.is_valid(ids[0]))