Skip to content

Utilities API ​

Common utilities for buffer management, encoding, multipart, metrics, and sessions.

Shared Helpers ​

httpx.common provides reusable helpers used across client/server/core modules.

  • queryValue(query, key): Get a query parameter value from a raw query string.
  • parseSetCookiePair(set_cookie): Parse the first name=value pair from a Set-Cookie header value.
  • cookieValue(cookie_header, name): Read a cookie value from a request Cookie header.
  • buildSetCookieHeader(allocator, name, value, options): Build a Set-Cookie header value with RFC 6265 style attributes.
  • mimeTypeFromPath(path): Resolve a best-effort MIME type from file extension.
  • mimeTypeFromPathOr(path, fallback): Resolve MIME from extension with an explicit fallback.
  • mimeTypeFromPathWith(path, mappings, fallback): Resolve MIME using caller-provided external mappings.
  • MimeMapping: Extension-to-MIME pair type for external mapping lists.
  • defaultMimeMappings: Built-in mapping table exported for extension/composition.
  • CookieOptions: Cookie attributes (Path, Domain, Max-Age, SameSite, Secure, HttpOnly).
  • SameSite: Enum values lax, strict, none.

Root-level aliases:

  • httpx.queryValue(...)
  • httpx.parseSetCookiePair(...)
  • httpx.mimeTypeFromPath(...)
  • httpx.mimeTypeFromPathOr(...)
  • httpx.mimeTypeFromPathWith(...)
  • httpx.MimeMapping
  • httpx.defaultMimeMappings
  • httpx.CookieOptions
  • httpx.SameSite
  • httpx.encodeVarInt(...)
  • httpx.decodeVarInt(...)

WebSocket Protocol ​

See Protocol API for the full WebSocket section. Root-level aliases:

  • httpx.isWebSocketUpgrade(req) — checks upgrade headers
  • httpx.wsExtractKey(req) — returns Sec-WebSocket-Key value
  • httpx.wsAcceptKey(key, allocator) — computes Sec-WebSocket-Accept
  • httpx.wsEncodeFrame(allocator, opcode, payload, fin, masked, mask_key) — low-level frame encoder
  • httpx.wsDecodeFrame(allocator, data) — decode one frame, returns WsDecodeResult
  • httpx.wsTextFrame(allocator, text) — encode server text frame
  • httpx.wsBinaryFrame(allocator, data) — encode server binary frame
  • httpx.wsPingFrame(allocator, data) — encode ping frame
  • httpx.wsPongFrame(allocator, data) — encode pong frame
  • httpx.wsCloseFrame(allocator, code, reason) — encode close frame
  • httpx.WsOpcode — frame opcode enum
  • httpx.WsFrame — decoded frame struct
  • httpx.WsCloseCode — close status codes
  • httpx.WsDecodeResult — { frame, consumed }
  • httpx.WS_GUID — RFC 6455 magic GUID

Multipart Form Data ​

RFC 2046 multipart/form-data builder and parser.

MultipartBuilder ​

MethodDescription
init(allocator, boundary)Create a builder with a boundary string
addField(name, value)Append a text form field part
addFile(name, filename, content_type, data)Append a file upload part
build()Finalize and return the complete body (caller owns)
contentType()Return the Content-Type header value (caller owns)
deinit()Release builder resources

extractMultipartBoundary(content_type) ​

Extracts the boundary value from a Content-Type header. Returns null if no boundary is present. Handles both quoted and unquoted boundary parameters.

Root-level alias: httpx.extractMultipartBoundary(...).

parseMultipart(allocator, body, boundary) ​

Parses a complete multipart body. Returns ParsedParts; call .deinit() when done.

Root-level alias: httpx.parseMultipart(...).

Part ​

FieldTypeDescription
name[]const u8Form field name
filename?[]const u8File name for uploads, null for text fields
content_type[]const u8Part content type (defaults to "text/plain")
data[]const u8Raw body bytes (slice into ParsedParts buffer)
headers[]const [2][]const u8All raw header pairs

ParsedParts ​

MemberDescription
parts[]Part — parsed parts slice
deinit()Free all allocated memory

Metrics and Observability ​

Thread-safe, allocation-free request/response metrics using atomic operations.

Metrics ​

MethodDescription
init()Create a zeroed Metrics instance
initWithCallback(fn)Create with a custom event callback
recordRequest()Increment total requests
recordResponse(status, bytes, latency_ns)Record response, update status buckets and latency
recordBytesSent(bytes)Increment bytes sent
recordError()Increment error counter
connectionOpened()Increment active connections
connectionClosed()Decrement active connections
reset()Reset all counters to zero
snapshot()Return a MetricsSnapshot

MetricsSnapshot ​

FieldTypeDescription
total_requestsu64Total requests recorded
total_responsesu64Total responses recorded
active_connectionsi64Current open connections
errorsu64Total errors
bytes_sentu64Total bytes sent
bytes_receivedu64Total bytes received
responses_2xxu642xx response count
responses_3xxu643xx response count
responses_4xxu644xx response count
responses_5xxu645xx response count
avg_latency_nsu64Average latency in nanoseconds
min_latency_nsu64Minimum latency in nanoseconds
max_latency_nsu64Maximum latency in nanoseconds
MethodReturnsDescription
errorRate()f64errors / total_requests
successRate()f64responses_2xx / total_responses
print()voidPrint a human-readable summary to stderr

MetricsEvent ​

Tagged union passed to the optional callback:

  • .request — a request was recorded
  • .response — { status: u16, bytes: u64, latency_ns: u64 }
  • .bytes_sent — u64
  • .err — an error was recorded
  • .connection_open / .connection_close

MetricsCallbackFn ​

*const fn (event: MetricsEvent) void

Root-level aliases: httpx.Metrics, httpx.MetricsSnapshot, httpx.MetricsEvent, httpx.MetricsCallbackFn.

Session Store ​

In-memory server-side sessions with TTL expiry.

SessionStore ​

MethodReturnsDescription
init(allocator, config)SessionStoreCreate a store with the given config
deinit()voidRelease all resources
create()![SESSION_ID_LEN * 2]u8Create a new session, return hex ID
set(hex_id, key, value)!voidSet a key in the session (duplicates value)
get(hex_id, key)?[]const u8Get a value; null if not found or expired
delete(hex_id)voidRemove a session
exists(hex_id)boolTrue if session exists and is not expired
evictExpired()usizeRemove expired sessions, returns count removed
count()usizeNumber of sessions in the store

SessionConfig ​

FieldDefaultDescription
ttl_ms1_800_000Session TTL in milliseconds since last access
cookie_name"session_id"Cookie name for session ID
max_sessions0Max sessions (0 = unlimited)

Constants ​

  • SESSION_ID_LEN = 32 — raw session ID byte length
  • DEFAULT_TTL_MS = 1_800_000 — 30 minutes

Root-level aliases: httpx.SessionStore, httpx.SessionConfig, httpx.SESSION_ID_LEN.

IO Utilities ​

Centralized in src/util/any_io.zig.

  • defaultIo() — returns the appropriate std.Io for test or runtime context
  • sleepMs(ms: u64) — sleep using the canonical IO
  • sleepMsI(ms: i64) — sleep using the canonical IO (signed)
  • AnyReader — type-erased reader with read, readByte, readNoEof
  • AnyWriter — type-erased writer with write, writeAll, print

Buffers ​

Buffer ​

Dynamic, growable byte buffer.

  • init(allocator, capacity) — create buffer
  • append(bytes) — append bytes
  • toOwnedSlice() — return owned slice
  • clear() — reset without deallocating
  • deinit() — release memory

RingBuffer ​

Circular buffer for streaming data.

  • init(allocator, size) — create ring buffer
  • writeBytes(bytes) — write bytes, returns bytes written
  • readBytes(buf) — read available bytes
  • getAvailable() — bytes available to read
  • getFreeSpace() — bytes available to write

FixedBuffer ​

Stack-allocated fixed-size buffer with no heap allocation.

zig
var buf = FixedBuffer(64){};

Encoding ​

Base64 ​

RFC 4648 base64 with standard and URL-safe alphabets.

  • encode(allocator, data) — encode to base64
  • decode(allocator, data) — decode from base64
  • encodeUrl(allocator, data) — URL-safe encoding

Hex ​

  • encode(allocator, data) — hex encode
  • decode(allocator, data) — hex decode

PercentEncoding ​

RFC 3986 URL encoding.

  • encode(allocator, input) — percent-encode
  • decode(allocator, input) — percent-decode

JSON ​

json.JsonBuilder ​

Fluent builder for constructing JSON strings.

zig
var jb = httpx.json.JsonBuilder.init(allocator);
defer jb.deinit();

try jb.beginObject();
try jb.key("name");
try jb.string("alice");
try jb.key("age");
try jb.number(30);
try jb.endObject();

const s = try jb.toSlice();
defer allocator.free(s);
  • beginObject() / endObject()
  • beginArray() / endArray()
  • key(name) / string(val) / number(val) / boolean(val) / nullValue()

Compression ​

Content-Encoding negotiation, compression, and decompression for gzip, deflate, Brotli, and Zstd.

ContentEncoding ​

Enum representing supported Content-Encoding values.

VariantDescription
.gzipgzip (RFC 1952)
.deflateDEFLATE (RFC 1951)
.brBrotli (RFC 7932)
.zstdZstandard
.identityNo encoding (pass-through)

ContentEncoding Constants and Methods ​

MemberDescription
ContentEncoding.ALLArray of all supported encodings: [_]ContentEncoding{ .gzip, .deflate, .br, .zstd, .identity }
toString()Convert to wire-format string (e.g., .gzip → "gzip")
fromString(str)Parse from a string; returns ?ContentEncoding (case-insensitive)
buildAcceptEncoding(encodings)Build an Accept-Encoding header value from a slice of encodings

httpx.decompress() ​

zig
pub fn decompress(allocator: Allocator, encoding: ContentEncoding, data: []const u8) ![]u8

Decompresses body content based on the provided Content-Encoding. The caller owns the returned slice.

httpx.compress() ​

zig
pub fn compress(allocator: Allocator, encoding: ContentEncoding, data: []const u8) ![]u8

Compresses data using the specified encoding. The caller owns the returned slice.

Root-level aliases: httpx.ContentEncoding, httpx.decompress, httpx.compress.

SSE (Server-Sent Events) ​

sse.Event ​

FieldTypeDefaultDescription
data[]const u8(required)Event payload body
event?[]const u8nullOptional SSE event name
id?[]const u8nullOptional event id
retry_ms?u32nullOptional client reconnect hint

Event.format(allocator) ​

Serializes an SSE event to wire format. Caller owns the returned slice.

parseSseStream(allocator, data, on_event) ​

Parses a raw SSE stream, invoking the callback for each complete event. Returns the number of events parsed.

zig
fn onEvent(event: sse.Event) void {
    std.debug.print("event: {s}\n", .{event.data});
}
const count = httpx.parseSseStream(allocator, raw_data, onEvent);

Root-level alias: httpx.parseSseStream(...).

Released under the MIT License.