Something went wrong. Try again.
An HTTP library for Zig 0.17, server and client, HTTP/1.0 through HTTP/3, with the protocol in a module that owns no socket.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>// SPDX-License-Identifier: MIT
//! One response, as a handler writes it.//!//! A status, a set of fields, and a body — and nothing about framing. The//! handler says how long the body is going to be, in `Length`, and the driver//! for whichever version is in use turns that into a `Content-Length`, a//! chunked transfer coding, a closed connection or a sequence of DATA frames.//! That is the whole reason this type exists rather than the handler writing//! to the socket: it is the seam that lets one handler serve HTTP/1.0,//! HTTP/1.1 and, when there is a driver for them, HTTP/2 and HTTP/3.//!//! Which is also why `Content-Length`, `Transfer-Encoding` and `Connection`//! set by hand are ignored. The first two are framing and belong to the//! driver; the third is an HTTP/1.1 connection-management field that HTTP/2//! makes a connection error to send at all.//!//! ## Order of operations//!//! Set the status and the fields, then call `beginBody` once, write to the//! writer it returns, then `end`. `send` and the other conveniences do all//! three. Setting a field after `beginBody` is a programmer error and//! asserts: by then the head is on the wire and there is nowhere for it to//! go.
const std = @import("std");const Io = std.Io;const Allocator = std.mem.Allocator;const assert = std.debug.assert;
const protocol = @import("../protocol.zig");const coding = protocol.coding;const compression = @import("compression.zig");const Headers = protocol.Headers;const Length = protocol.Length;const Status = protocol.Status;const Version = protocol.Version;
// For the doctests alone.const http1 = @import("../http1.zig");const transport = @import("../transport.zig");const Request = @import("Request.zig");
const Response = @This();
/// The status to send. `.ok` unless the handler says otherwise.status: Status = .ok,/// The fields to send. Neither the names nor the values are copied, so both/// must outlive `end`; `printHeader` is the way to add one that has to be/// computed.headers: Headers,/// RFC 9110 §6.5: fields sent *after* the content, for things that are not/// known until it has been produced — a checksum, a signature, how long the/// work took, why a stream stopped early.////// Filled in any time before the response ends; the driver writes them when/// it finishes the body. Which driver is running decides whether they can be/// sent at all, and §6.6.2 is explicit that "a trailer section is only/// possible when the message framing allows it": over HTTP/1.1 that means a/// chunked coding, so a response whose length was declared has nowhere to put/// them and they are dropped. Over HTTP/2 and HTTP/3 they are a second field/// section and always possible.////// Dropping rather than failing is the specified behaviour rather than a/// shortcut — a trailer field is by construction something the recipient may/// not receive, which is also why §6.5.1 forbids putting anything the/// recipient *needs* in one. `isForbiddenTrailer` is that list, and the/// drivers refuse those names on the way out rather than trusting a handler/// to have read the section.trailers: Headers = .empty,/// Scratch for the length of this exchange. The same arena as/// `Request.arena`.arena: Allocator,/// The version this response will be framed in, which is the version of the/// request unless the server had to fall back.version: Version,state: State = .head,context: ?*anyopaque,vtable: *const VTable,/// What the client said it would take, borrowed from the request that asked.////// The driver fills it in, because the driver is what has both halves: this/// struct is written against a response and never sees the request that/// caused it.accept_encoding: ?[]const u8 = null,/// Whether to code the body, and how. Null is a server that does not.compress: ?compression.Config = null,/// The compressor, once `beginBody` has decided to use one. `end` finishes/// it — §2.2 of RFC 1952's footer is not written by a flush — before letting/// the driver end the body.compressor: ?*coding.Compressor = null,
pub const State = enum { /// Nothing has been written. The status and the fields can still change. head, /// The head is on the wire and the body is being written. body, /// The response is complete. ended, /// The connection is no longer speaking HTTP. `upgrade` handed the byte /// stream to the handler, and nothing here may touch it again. upgraded,};
pub const Error = error{ /// The connection failed. Nothing more will go out on it. WriteFailed, OutOfMemory, /// A field name that is not a token, or a value carrying an octet that /// would change the framing of the message around it. InvalidField, /// The body was longer than the length that was declared for it, or /// `end` was reached before it was as long as declared. Either way the /// message on the wire is not the one that was described, so the /// connection cannot be reused. LengthMismatch, /// The fields come to more than the peer said it would accept, which /// HTTP/3's SETTINGS_MAX_FIELD_SECTION_SIZE lets it say. Nothing was /// sent, so a head that failed this way can still be answered with a /// smaller one. FieldSectionTooLarge,};
pub const VTable = struct { /// Commits the status and the fields, and returns the writer the body /// goes to. Called at most once. beginBody: *const fn (res: *Response, length: Length) Error!*Io.Writer, /// Finishes the body — the terminating chunk, the end of the stream, /// whatever the version needs — and flushes. end: *const fn (res: *Response) Error!void, /// Sends an interim response: a `1xx` with fields and no body, which is /// followed by the real response later. sendInterim: *const fn (res: *Response, status: Status, headers: *const Headers) Error!void, /// Stops speaking HTTP and hands the byte stream over. Null for a driver /// that has no way to do it. upgrade: ?*const fn (res: *Response, protocol_name: []const u8) UpgradeError!Upgrade = null,};
/// The byte stream, once it is no longer carrying HTTP.////// Both halves are exactly where HTTP left off: anything the client sent/// after its request head, and before the `101` went out, is still buffered/// in `input` and will be read first. That is the property a protocol switch/// lives or dies by — a client that pipelines its first frames behind the/// handshake must not lose them — and it is why `upgrade` hands back the/// reader the server was already using rather than a fresh one.pub const Upgrade = struct { input: *Io.Reader, output: *Io.Writer,};
pub const UpgradeError = Error || error{ /// The client did not offer this protocol. RFC 9110 §7.8 forbids /// switching to one it did not list, and this is that rule. NotOffered, /// Nothing here can switch protocols: an HTTP/1.0 client, or a driver /// for a version where `Upgrade` does not exist. UpgradeUnavailable, /// The request has a body that the handler did not read. Its remaining /// octets are still in front of the new protocol's first octet, and /// handing the stream over with them there would corrupt it. BodyNotConsumed,};
/// Stops speaking HTTP on this connection and hands the byte stream to the/// handler.////// This is the `Upgrade` mechanism of RFC 9110 §7.8: the handler sees a/// request offering to switch, decides, and gets back a reader and a writer/// that are no longer anybody else's business. `101 Switching Protocols` goes/// out first, carrying whatever fields have been set — which for a WebSocket/// is where `Sec-WebSocket-Accept` belongs.////// ## It is not a callback, on purpose////// The obvious shape for this is a callback registered with the server: "when/// somebody upgrades to `websocket`, call me with the socket". This is a/// method that returns the stream instead, and the reason is lifetime. A/// callback invoked after the handler returns would be handed a connection/// whose owner had already moved on, which means the server has to keep it/// alive on the callback's behalf and the two have to agree about when it is/// finished. Returning the stream to the handler that is already running/// keeps the whole thing in one stack frame: the handler speaks the new/// protocol for as long as it likes, returns when it is done, and the/// connection closes where every other connection closes.////// So a WebSocket handler is an ordinary handler that, at the top, checks/// whether it was offered the upgrade, computes the accept token, calls this,/// and then never returns to HTTP.////// ## After it returns////// The response is over — the status and the fields cannot change, no body/// may be written, and this connection will not serve another request. The/// server closes the connection once the handler returns.////// If it returns an error instead, nothing has been written and nothing has/// changed: the handler can go on to send an ordinary response, which for a/// refused upgrade is usually `426 Upgrade Required`.pub fn upgrade(res: *Response, protocol_name: []const u8) UpgradeError!Upgrade { assert(res.state == .head); const switchProtocols = res.vtable.upgrade orelse return error.UpgradeUnavailable; // Nothing is touched until the driver has agreed. A refused upgrade has // to leave the response exactly as it found it, because the handler's // next move is to send an ordinary one instead — `426 Upgrade Required`, // usually — and it would go out as a `101` if the status had already // been changed on the way in. const stream = try switchProtocols(res, protocol_name); res.status = .switching_protocols; res.state = .upgraded; return stream;}
test upgrade { const Shout = struct { fn serve(req: *Request, res: *Response) anyerror!void { if (!req.offersUpgrade("shout")) return res.sendStatus(.upgrade_required); // Refused, and the response is untouched for the `426` to follow. try std.testing.expectError(error.NotOffered, res.upgrade("whisper"));
const stream = try res.upgrade("shout"); // HTTP is over: what follows is whatever "shout" says it is. const line = try stream.input.takeDelimiterInclusive('\n'); for (line) |ch| try stream.output.writeByte(std.ascii.toUpper(ch)); try stream.output.flush(); } }; const got = try exchange( "GET /chat HTTP/1.1\r\nHost: a\r\nConnection: upgrade\r\nUpgrade: shout\r\n\r\nhello\n", Shout.serve, ); defer std.testing.allocator.free(got); try std.testing.expectEqualStrings( "HTTP/1.1 101 Switching Protocols\r\nConnection: Upgrade\r\nUpgrade: shout\r\n\r\nHELLO\n", got, );}
/// Adds a field, keeping any other field of the same name. Which is what/// `Set-Cookie` and `Via` want, and not what `Content-Type` wants.pub fn addHeader(res: *Response, name: []const u8, value: []const u8) Error!void { assert(res.state == .head); return res.headers.append(res.arena, name, value) catch |err| switch (err) { error.InvalidField => error.InvalidField, error.OutOfMemory => error.OutOfMemory, };}
test addHeader { const Cookies = struct { fn serve(req: *Request, res: *Response) anyerror!void { _ = req; try res.addHeader("Set-Cookie", "a=1"); try res.addHeader("Set-Cookie", "b=2"); // A value that would end the field early is refused, not sent. try std.testing.expectError(error.InvalidField, res.addHeader("Set-Cookie", "c=3\r\nX: y")); try res.send(""); } }; const got = try exchange("GET / HTTP/1.1\r\nHost: a\r\n\r\n", Cookies.serve); defer std.testing.allocator.free(got); try std.testing.expectEqualStrings( "HTTP/1.1 200 OK\r\nContent-Length: 0\r\nSet-Cookie: a=1\r\nSet-Cookie: b=2\r\n\r\n", got, );}
/// Replaces every field of this name with one holding `value`.pub fn setHeader(res: *Response, name: []const u8, value: []const u8) Error!void { assert(res.state == .head); return res.headers.set(res.arena, name, value) catch |err| switch (err) { error.InvalidField => error.InvalidField, error.OutOfMemory => error.OutOfMemory, };}
test setHeader { const Json = struct { fn serve(req: *Request, res: *Response) anyerror!void { _ = req; try res.setHeader("Content-Type", "text/plain"); // Changed its mind: one `Content-Type` goes out, not two. try res.setHeader("Content-Type", "application/json"); try res.send("{}"); } }; const got = try exchange("GET / HTTP/1.1\r\nHost: a\r\n\r\n", Json.serve); defer std.testing.allocator.free(got); try std.testing.expectEqualStrings( "HTTP/1.1 200 OK\r\nContent-Length: 2\r\nContent-Type: application/json\r\n\r\n{}", got, );}
/// `setHeader` with the value formatted into the exchange's arena, for the/// common case of a value that has to be computed and has nowhere else to/// live.pub fn printHeader( res: *Response, name: []const u8, comptime fmt: []const u8, args: anytype,) Error!void { const value = std.fmt.allocPrint(res.arena, fmt, args) catch return error.OutOfMemory; return res.setHeader(name, value);}
test printHeader { const Cached = struct { fn serve(req: *Request, res: *Response) anyerror!void { _ = req; const max_age: u32 = 60 * 60; try res.printHeader("Cache-Control", "public, max-age={d}", .{max_age}); try res.send(""); } }; const got = try exchange("GET / HTTP/1.1\r\nHost: a\r\n\r\n", Cached.serve); defer std.testing.allocator.free(got); try std.testing.expectEqualStrings( "HTTP/1.1 200 OK\r\nContent-Length: 0\r\nCache-Control: public, max-age=3600\r\n\r\n", got, );}
/// Commits the status and the fields and returns the writer for the body.////// `length` is a promise. `.exact` says how many octets are coming and the/// driver will hold the body to it; `.unknown` says the handler does not know/// yet, which costs a chunked transfer coding in HTTP/1.1 and a closed/// connection in HTTP/1.0; `.none` says there is no body, which is not the/// same as an empty one.////// On a server that compresses (`compress` set), this is also where the/// coding is chosen. When it is, the fields gain `Content-Encoding`, the/// writer returned is the compressor's rather than the driver's, and an/// `.exact` length goes out as `.unknown`, because the coded length is not/// known until the body has been written.pub fn beginBody(res: *Response, length: Length) Error!*Io.Writer { assert(res.state == .head);
// §8.4: a content coding is applied to the representation, so this // happens above the framing and before it -- which is also why it is here // and not in a driver. All three call this, and none of them has a line // about codings in it. var effective = length; var chosen: ?coding.Coding = null; if (res.compress) |config| chosen = res.negotiateCoding(config, &effective);
const w = try res.vtable.beginBody(res, effective); res.state = .body;
const want = chosen orelse return w; // The window and the compressor both outlive this call and are pointed at // by what it returns, so neither may be on this stack. The arena is the // exchange's and goes away with it. const window = res.arena.alloc(u8, coding.window_len) catch return error.OutOfMemory; const c = res.arena.create(coding.Compressor) catch return error.OutOfMemory; // gzip is the only coding `Coding.supported` admits, and `wants` only // ever returns one from `config.codings`. An assertion rather than a // silent fallthrough, so that adding a second coding to that list without // teaching this line about it stops here rather than labelling one // coding's octets with another's name. assert(want == .gzip); c.* = coding.gzipCompressor(w, window, res.compress.?.level) catch return error.WriteFailed; res.compressor = c; return &c.writer;}
test beginBody { const Stream = struct { fn serve(req: *Request, res: *Response) anyerror!void { _ = req; // Nobody knows how long this is going to be until it is done, // which over HTTP/1.1 is a chunked body. const w = try res.beginBody(.unknown); for (0..3) |i| { try w.print("line {d}\n", .{i}); try w.flush(); } try res.end(); } }; const got = try exchange("GET / HTTP/1.1\r\nHost: a\r\n\r\n", Stream.serve); defer std.testing.allocator.free(got); try std.testing.expectEqualStrings( "HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n" ++ "7\r\nline 0\n\r\n7\r\nline 1\n\r\n7\r\nline 2\n\r\n0\r\n\r\n", got, );}
/// Decides the coding and says so in the fields, before the head is committed.////// `length` is rewritten because a coded body has a length nobody knows until/// it has been produced: §8.6's `Content-Length` counts the coded octets, and/// there is no way to count them in advance. `.unknown` is what every driver/// already does for a body of undeclared length -- a chunked coding over/// HTTP/1.1, DATA frames over the other two -- so a compressed response costs/// the framing it would have had, and nothing else changes.fn negotiateCoding(res: *Response, config: compression.Config, length: *Length) ?coding.Coding { if (!statusAllowsBody(res.status)) return null; // A handler that coded it already has said so, and coding it twice would // be this library disagreeing with the handler about the representation. if (res.headers.get("content-encoding") != null) return null;
const content_type = res.headers.get("content-type"); if (!compression.negotiable(config, content_type)) return null;
// §12.5.4: the representation this server sends for this resource depends // on `Accept-Encoding`, and it says so whether or not it happens to have // compressed *this* one. A cache told only about the compressed times // would keep an identity body under a key that a gzip-accepting client // matches, and serve the wrong one ever after. res.addHeader("Vary", "Accept-Encoding") catch return null;
const want = compression.wants(config, res.accept_encoding, content_type, length.*) orelse return null; res.setHeader("Content-Encoding", want.name()) catch return null; length.* = .unknown; return want;}
/// RFC 9110 §6.5.1: whether a field may not be sent in a trailer section.////// The list is not arbitrary. A trailer arrives after the recipient has/// already acted on the head and, for a proxy, after it has already forwarded/// it — so anything that would change how the message is *framed*, *routed*,/// *cached* or *authenticated* arrives too late to be obeyed and is a way to/// say one thing to a cache and another to whatever is behind it. §6.5.1/// names the classes; these are the fields in them that this library can/// meet.pub fn isForbiddenTrailer(name: []const u8) bool { const forbidden = [_][]const u8{ // Framing: the recipient has already decided where the body ends. "transfer-encoding", "content-length", "host", // Routing and request modifiers. "te", "expect", "max-forwards", "cache-control", "expires", "pragma", "age", "vary", "warning", // Authentication, which a recipient acted on before the body. "authorization", "proxy-authorization", "www-authenticate", "proxy-authenticate", "set-cookie", "cookie", // How to interpret the content, which is needed to read it at all. "content-encoding", "content-type", "content-range", "trailer", }; for (forbidden) |f| { if (std.ascii.eqlIgnoreCase(name, f)) return true; } return false;}
test isForbiddenTrailer { // Something only known once the body has been produced. try std.testing.expect(!isForbiddenTrailer("Server-Timing")); try std.testing.expect(!isForbiddenTrailer("Digest")); // Framing, caching and authentication, which arrive too late to obey. try std.testing.expect(isForbiddenTrailer("Content-Length")); try std.testing.expect(isForbiddenTrailer("cache-control")); try std.testing.expect(isForbiddenTrailer("Set-Cookie"));}
/// Finishes the response: finishes the content coding, if there is one, then/// has the driver end the body — writing `trailers`, where the framing has/// room for them — and flush.////// `error.LengthMismatch` is a body shorter than the `.exact` length/// `beginBody` was given, which the HTTP/1.1 and HTTP/2 drivers check for/// here. The connection is not reused after it.pub fn end(res: *Response) Error!void { assert(res.state == .body); // §2.2 of RFC 1952: the final block and the footer, which `flush` does not // write. Without this the body stops mid-member and a recipient that // checks says so while one that does not is quietly given less than was // sent. if (res.compressor) |c| c.finish() catch return error.WriteFailed; try res.vtable.end(res); res.state = .ended;}
test end { const Timed = struct { fn serve(req: *Request, res: *Response) anyerror!void { _ = req; const w = try res.beginBody(.unknown); try w.writeAll("done"); // Known only now, so it goes after the body. try res.trailers.append(res.arena, "Server-Timing", "total;dur=12"); try res.end(); } }; const got = try exchange("GET / HTTP/1.1\r\nHost: a\r\n\r\n", Timed.serve); defer std.testing.allocator.free(got); try std.testing.expectEqualStrings( "HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n" ++ "4\r\ndone\r\n0\r\nServer-Timing: total;dur=12\r\n\r\n", got, );}
/// Sends `bytes` as the whole body, with its length declared up front.pub fn send(res: *Response, bytes: []const u8) Error!void { const w = try res.beginBody(.{ .exact = bytes.len }); try w.writeAll(bytes); return res.end();}
test send { const Hello = struct { fn serve(req: *Request, res: *Response) anyerror!void { _ = req; try res.setHeader("Content-Type", "text/plain"); try res.send("hello"); } }; const got = try exchange("GET / HTTP/1.1\r\nHost: a\r\n\r\n", Hello.serve); defer std.testing.allocator.free(got); try std.testing.expectEqualStrings( "HTTP/1.1 200 OK\r\nContent-Length: 5\r\nContent-Type: text/plain\r\n\r\nhello", got, );}
/// `send` with the body formatted into the exchange's arena.pub fn sendPrint(res: *Response, comptime fmt: []const u8, args: anytype) Error!void { const body = std.fmt.allocPrint(res.arena, fmt, args) catch return error.OutOfMemory; return res.send(body);}
test sendPrint { const Echo = struct { fn serve(req: *Request, res: *Response) anyerror!void { try res.sendPrint("{s} {s}", .{ req.method.name, req.target.path }); } }; const got = try exchange("GET /where HTTP/1.1\r\nHost: a\r\n\r\n", Echo.serve); defer std.testing.allocator.free(got); try std.testing.expectEqualStrings("HTTP/1.1 200 OK\r\nContent-Length: 10\r\n\r\nGET /where", got);}
/// Sends a status with a one-line body naming it, which is what an error/// response looks like when nobody has written a nicer one.////// The statuses that may not carry a body get none: a `204` with a body in it/// is a framing error, not a friendlier `204`.pub fn sendStatus(res: *Response, status: Status) Error!void { res.status = status; if (!statusAllowsBody(status)) { _ = try res.beginBody(.none); return res.end(); } try res.setHeader("Content-Type", "text/plain; charset=utf-8"); const phrase = status.phrase() orelse "Unknown"; return res.sendPrint("{d} {s}\n", .{ @backingInt(status), phrase });}
test sendStatus { const Missing = struct { fn serve(req: *Request, res: *Response) anyerror!void { _ = req; try res.sendStatus(.not_found); } }; const got = try exchange("GET / HTTP/1.1\r\nHost: a\r\n\r\n", Missing.serve); defer std.testing.allocator.free(got); try std.testing.expectEqualStrings( "HTTP/1.1 404 Not Found\r\nContent-Length: 14\r\n" ++ "Content-Type: text/plain; charset=utf-8\r\n\r\n404 Not Found\n", got, );}
/// Sends a redirect. `status` must be one of the `3xx` that carry a/// `Location`.pub fn redirect(res: *Response, status: Status, location: []const u8) Error!void { res.status = status; try res.setHeader("Location", location); return res.sendStatus(status);}
test redirect { const Moved = struct { fn serve(req: *Request, res: *Response) anyerror!void { _ = req; try res.redirect(.see_other, "/elsewhere"); } }; const got = try exchange("POST /form HTTP/1.1\r\nHost: a\r\nContent-Length: 0\r\n\r\n", Moved.serve); defer std.testing.allocator.free(got); try std.testing.expectEqualStrings( "HTTP/1.1 303 See Other\r\nContent-Length: 14\r\nLocation: /elsewhere\r\n" ++ "Content-Type: text/plain; charset=utf-8\r\n\r\n303 See Other\n", got, );}
/// Sends an interim `1xx` response, which is followed by the real one.////// `103 Early Hints` is the one worth sending: it lets a client start/// fetching the stylesheet while the server is still working out what the/// page says. Interim responses are silently dropped for an HTTP/1.0 client,/// which has no idea what to do with one.pub fn sendInterim(res: *Response, status: Status, headers: *const Headers) Error!void { assert(res.state == .head); assert(status.class() == .informational); return res.vtable.sendInterim(res, status, headers);}
test sendInterim { const Hinted = struct { fn serve(req: *Request, res: *Response) anyerror!void { _ = req; var hints: Headers = .empty; try hints.append(res.arena, "Link", "</style.css>; rel=preload; as=style"); try res.sendInterim(.early_hints, &hints); // ...and then the work the hint was sent ahead of. try res.send("page"); } }; const got = try exchange("GET / HTTP/1.1\r\nHost: a\r\n\r\n", Hinted.serve); defer std.testing.allocator.free(got); try std.testing.expectEqualStrings( "HTTP/1.1 103 Early Hints\r\nLink: </style.css>; rel=preload; as=style\r\n\r\n" ++ "HTTP/1.1 200 OK\r\nContent-Length: 4\r\n\r\npage", got, );}
test "an interim status with no phrase of its own is sent with none" { const Unnamed = struct { fn serve(req: *Request, res: *Response) anyerror!void { _ = req; try res.sendInterim(@fromBackingInt(199), &Headers.empty); try res.send(""); } }; const got = try exchange("GET / HTTP/1.1\r\nHost: a\r\n\r\n", Unnamed.serve); defer std.testing.allocator.free(got); try std.testing.expect(std.mem.startsWith(u8, got, "HTTP/1.1 199 \r\n\r\nHTTP/1.1 200 OK\r\n"));}
/// Whether a response with this status may carry a body at all (RFC 9110/// §6.4.1). Nothing to do with whether one is wanted — a `204` with a body is/// malformed however much the handler would like to explain itself.pub fn statusAllowsBody(status: Status) bool { return switch (status.class()) { .informational => false, else => switch (@backingInt(status)) { 204, 304 => false, else => true, }, };}
test statusAllowsBody { try std.testing.expect(statusAllowsBody(.ok)); try std.testing.expect(statusAllowsBody(.not_found)); try std.testing.expect(!statusAllowsBody(.no_content)); try std.testing.expect(!statusAllowsBody(.not_modified)); try std.testing.expect(!statusAllowsBody(.@"continue"));}
/// What a handler sends in answer to `request`, as the octets on the wire.////// For the doctests. A `Response` is made by a driver and handed to a/// handler, so the honest way to show one in use is to run a handler and look/// at what came out — HTTP/1.1 over `transport.memory`, because its framing/// is the one that reads as a string.fn exchange(request: []const u8, comptime serveFn: fn (*Request, *Response) anyerror!void) ![]u8 { const gpa = std.testing.allocator; var c: transport.memory.Connection = try .init(gpa, request, .{}); defer c.deinit(); var conn = c.connection(); try http1.serve(Io.failing, gpa, &conn, .initStateless(serveFn), .{ .send_date = false, .server_name = null, }); return gpa.dupe(u8, c.written());}
test { std.testing.refAllDecls(@This());}