http
import http from "http";
import io from "io";
var opts: http.Options = http.options();
opts.max_redirects = 5;
let r: http.Response = http.get("https://example.com/", opts) or {
io.eprintln("fetch failed: {err.desc()}");
return 1;
};
io.println("{r.status} {r.reason()}");
let ct: ?[]const u8 = r.header("Content-Type");
if (ct != null) { io.println("type {ct!}"); }
io.print(r.body);http is an HTTP client over net. One call sends
one request on a fresh HTTP/1.1 connection (Connection: close) and reads the whole
response into memory: the status, the head as received and the body. It
handles chunked transfer coding, Content-Length, bodies that end with
the connection, interim 1xx responses, timeouts, size limits and, when
you ask for them, redirects. A response with any status is a response:
a 404 is not an error.
https:// URLs go through TLS 1.3 in net
(net.tls_wrap): the server’s certificate is checked against tape’s
bundled roots, or the trust store in Options.trust, for the URL’s host,
and ALPN offers http/1.1. There is no option to skip the check: for a
server with a private certificate, trust its root (below).
// A server whose certificate comes from your own CA
var t: net.Trust = net.trust_from_pem(fs.read_file("corp-root.pem") or { return 1; }) or { return 1; };
defer t.free();
var opts: http.Options = http.options();
opts.trust = t.store();
let r: http.Response = http.get("https://intranet.example/status", opts) or { return 1; };A Client keeps connections for the next requests, runs
many requests at once, and speaks HTTP/2 to https servers that offer it.
For a loop you write, a Server is the server half
of HTTP/1.1 for one connection, and a ClientConn
the client half in the same shape.
Not covered (yet): streaming a body to a writer on the client side,
HTTP/3, compression (Accept-Encoding: identity is sent), cookies,
proxies, Expect: 100-continue on the client side, multipart forms, a
server that owns its sockets.
Requests
| Function | Does |
|---|---|
get(url, opts) -> Response | A GET of url |
request(req, opts) -> Response | Send req and read the whole response |
options() -> Options | The defaults, to change field by field |
parse_url(text) -> Url | The parts of an http or https URL |
pub enum Method : u8 { Get = 1; Head = 2; Post = 3; Put = 4; Delete = 5; Patch = 6; Options = 7; } // m.desc() is "GET", ...
pub struct Field { name: []const u8; value: []const u8; }
pub struct Request {
method: Method;
url: []const u8;
headers: []const Field; // extra request headers
body: []const u8; // sent with Content-Length when not empty
}let body: []const u8 = "\{\"name\": \"tape\"}";
let r: http.Response = http.request(http.Request {
method: http.Method.Post;
url: "http://127.0.0.1:8080/items";
headers: [http.Field { name: "Content-Type"; value: "application/json"; }];
body: body;
}, http.options()) or { return 1; };The request sent is the request line (POST /items HTTP/1.1), then
Host (with the port when it isn’t the scheme’s default, an IPv6 address
in brackets), User-Agent: tape-http, Accept-Encoding: identity,
Connection: close, your headers in order, Content-Length when there is
a body (and Content-Length: 0 for a POST, PUT or PATCH without
one), an empty line and the body. A User-Agent or Accept-Encoding of
yours replaces the client’s.
Some header mistakes are bugs in the calling program, so they trap instead
of returning an error: a header named Host, Content-Length,
Connection or Transfer-Encoding (the client sends those itself), a name
that isn’t an HTTP token, a value containing CR, LF or NUL (header
injection), and a negative limit in Options.
Clients
get and request open a connection for each request and close it after
the response. A program that makes many requests (a browser loading a
page’s scripts and images) keeps a Client instead. It keeps connections
for the next request to the same scheme, host and port, which saves the
connecting and, for https, the TLS handshake; it has many requests in
flight at once; and over https it offers HTTP/2, so a server that picks
it carries every request as a stream of one connection.
var c: http.Client = http.client();
defer c.close();
let a: http.Response = c.get("https://example.com/a.png", http.options()) or { return 1; };
let b: http.Response = c.get("https://example.com/b.png", http.options()) or { return 1; }; // the same connection| Function | What it does |
|---|---|
client() -> Client | A client with no connections yet |
c.get(url, opts) -> Response | get through the client’s connections |
c.request(req, opts) -> Response | request through the client’s connections |
c.start(req, opts) -> i64 | Queue a request and return its id; it is sent at the next wait (or get, request, get_all) |
c.wait() -> ?Done | The next request to finish, in any order; null when none is left |
c.wait_for(timeout) -> ?Done | The same, but null once timeout has passed with every request still pending; zero is a poll |
c.pending() -> i64 | The requests started and not yet taken by a wait |
c.get_all(urls, opts) -> Vec_Done | A GET of every URL at once; the results in the order of urls |
c.get_all_strings(urls, opts) -> Vec_Done | The same over []const string (a Vec_string’s slice()) |
c.close() | Closes every connection, drops what is in flight |
pub struct Done {
id: i64; // what start returned
response: Response;
error: ?HttpError;
}
// d.result() -> Response or HttpErrorEach request finishes on its own: one that fails (a refused connection, a
timeout) doesn’t stop the others, and a 404 is a response like any.
let urls: [3][]const u8 = ["https://example.com/a.js", "https://example.com/b.js", "https://cdn.example/c.css"];
var all: http.Vec_Done = c.get_all(urls[..], http.options());
for (i in 0..all.len()) {
let r: http.Response = all.get_ref(i).result() or {
io.eprintln("{urls[i]}: {err.desc()}");
continue;
};
io.println("{urls[i]}: {r.status}, {r.body.len} bytes");
}let first: i64 = c.start(http.Request { method: http.Method.Get; url: "https://example.com/"; headers: []; body: ""; }, opts);
let second: i64 = c.start(http.Request { method: http.Method.Post; url: "https://example.com/log"; headers: []; body: "hit"; }, opts);
while (true) {
let d: ?http.Done = c.wait();
if (d == null) { break; }
if (d!.id == first) { ... }
}How requests go out:
- HTTP/2. For
https, TLS offersh2thenhttp/1.1(ALPN). When the server picksh2, one connection to it carries every request as a stream, as many at once as the server allows (itsMAX_CONCURRENT_STREAMS; the rest wait for a stream to finish). Headers are compressed with HPACK; bodies flow within each side’s windows.c.http2 = falseturns it off. - HTTP/1.1. Otherwise each connection carries one request at a time,
up to
c.per_hostconnections to one server at once (6, as browsers do); more requests wait for one of them. A connection is kept for the next request when the response is HTTP/1.1 (or HTTP/1.0 withConnection: keep-alive), has noConnection: closeand its body ends by its length or its chunks; up to 8 idle ones are kept. - Sent again. A request the server did not process is sent again,
once: an HTTP/2 stream refused (
REFUSED_STREAM) or above aGOAWAY’s last stream, any method; an idempotent one (GET,HEAD,PUT,DELETE,OPTIONS) whose kept connection the server had closed, or whose HTTP/2 connection ended before the response. A server that answersHTTP_1_1_REQUIREDis reached over HTTP/1.1 from then on. - An HTTP/2 response’s
headreadsHTTP/2 200and then its headers as lines, sor.headerandr.headerswork the same (names arrive in lowercase;r.reason()is"").
Nothing is sent until you wait: start only queues, so start a batch, then
wait. read_timeout is each request’s own limit: when nothing comes on its
connection for that long, it fails with TimedOut. Connecting (and the TLS
handshake) to a new server happens inside the wait and holds it up
meanwhile. Don’t copy a Client, and use it from one thread at a time.
A loop that has other work to do doesn’t block in wait on one slow
server: c.wait_for(timeout) gives up after timeout and returns null,
the requests still pending and what has arrived of each kept for the next
call. c.wait_for(time.millis(0)) only picks up a request that is already
whole. c.pending() tells a null from the timeout (requests still in
flight) from one with nothing left:
while (running) {
serve_sessions(); // the loop's own work
while (true) {
let d: ?http.Done = c.wait_for(time.millis(40));
if (d == null) { break; } // this slice is up, or nothing in flight
deliver(d!);
}
if (c.pending() == 0) { idle(); }
}A null from wait_for is not a failure: the requests are untouched, and
their read_timeout keeps counting across calls, so a server that stays
silent still fails its request on time.
Options
pub struct Options {
max_redirects: i64; // 0: do not follow (the default)
max_body: i64; // bytes
max_head: i64; // status line and headers, bytes
connect_timeout: ?time.Duration;
read_timeout: ?time.Duration; // each receive and each send
trust: ?*const x509.TrustStore; // https; null: tape's bundled roots
}options() gives no redirects, a 64 MiB body limit, a 64 KiB head limit,
30 seconds for connecting and 30 seconds for each read and write. Build
Options with options() and change what you need: a zero-filled
Options would refuse every body. A null timeout waits forever.
connect_timeout covers resolving the host and connecting (racing its
addresses, as net.connect_host does).
read_timeout is the longest wait for the next bytes, not a limit on the
whole response: a slow server that keeps sending is not cut off. For
https, connect_timeout also bounds the TLS handshake.
trust is the set of roots an https server’s certificate must chain to:
null is tape’s bundled roots (net.bundled_trust); a
net.Trust you build gives its store(). To also trust
the operating system’s roots, build a Trust with add_bundled and
add_system.
Responses
pub struct Response {
status: i64;
head: string; // status line and header lines as received
body: string;
url: string; // the URL finally fetched (after redirects)
}| Method | Does |
|---|---|
r.reason() -> []const u8 | The status line’s reason phrase ("Not Found"; "" when there is none) |
r.header(name) -> ?[]const u8 | The first header called name, ignoring case; its value without surrounding spaces |
r.headers() -> HeaderIter | Every header in the order received, repeated ones included |
The headers are not copied out: header and headers look them up in
r.head and return views into it, valid while r is.
var it: http.HeaderIter = r.headers();
while (true) {
let f: ?http.Field = it.next();
if (f == null) { break; }
io.println("{f!.name}: {f!.value}");
}How much body there is follows RFC 9112:
- none for a
HEADrequest and for1xx,204and304responses; - with
Transfer-Encoding: chunked, the chunks (any chunk extensions ignored, trailers read and dropped); aContent-Lengthnext to it is ignored. Any other transfer coding is aBadHeadererror; - with
Content-Length, exactly that many bytes. Repeated values must agree; - otherwise everything until the server closes the connection (how HTTP/1.0 servers send).
Interim 1xx responses (100 Continue, 103 Early Hints) are skipped
(a 101 Switching Protocols to a request that asked for no upgrade is
BadStatusLine);
r.head is the final response’s head. Lines ending in a bare LF are
accepted as well as CRLF. Folded header lines (a line starting with a
space or a tab) are refused.
Redirects
With max_redirects above 0, a 301, 302, 303, 307 or 308 with a
Location is followed, up to that many times. The Location may be an
absolute URL or a reference resolved against the current URL (/path,
../path, ?query, //host/path), as RFC 3986 resolves them.
303, and301or302after aPOST, continue as aGETwithout the body (aHEADstays aHEAD).307and308keep the method and the body.- A redirect to another origin (another host, scheme or port) drops your
AuthorizationandCookieheaders for the rest of the request. httpstohttpis refused (InsecureRedirect).- More than
max_redirectsisTooManyRedirects; a missingLocation, or one that isn’t a usablehttp/httpsURL, isBadRedirect.
r.url is the URL of the response you got. With redirects off (the
default), a 3xx is returned like any other response, Location and all.
URLs
pub struct Url { scheme: []const u8; host: []const u8; port: u16; target: []const u8; }parse_url reads scheme://host[:port][/path][?query][#fragment]:
- the scheme is
httporhttpsin any case (schemeis the lowercase name); anything else isUnsupportedScheme; - the host is a name (letters, digits,
-,.,_), an IPv4 address, or an IPv6 address in brackets (hostwithout them; zone ids are refused); - the port is 1 to 65535; without one (or with an empty one,
h:/), the scheme’s default, 80 or 443; targetis the path and query exactly as written, the fragment cut off,"/"when both are empty (http://h?qhas the target?qand is requested as/?q).
There is no decoding or normalization: the target goes on the wire as
written. Bytes that can’t appear in a request target are refused rather
than guessed at: spaces, control characters, bytes above 127 (percent-encode
them, encoding can) and a % not followed by two hex
digits. User information (user:password@) is refused too: put
credentials in an Authorization header.
| Text | parse_url |
|---|---|
http://example.com | http, example.com, 80, / |
HTTPS://Example.com:8443/a/b?q=1#top | https, Example.com, 8443, /a/b?q=1 |
http://[2001:db8::1]:8080/ | http, 2001:db8::1, 8080, / |
http://user:pw@example.com/ | BadUrl |
ftp://example.com/file | UnsupportedScheme |
Errors
pub tagged HttpError {
Io { e: io.IoError; } // connecting, sending, receiving
Tls { e: tls.TlsError; } // https: the handshake, the certificate, the records
Http { e: ProtocolError; } // the URL, the response, redirects
H2 { e: h2.H2Error; } // a Client's HTTP/2 connection: the server's error codes, the limits
}err.desc() gives the text of any. The transport errors are
io.IoError values from net: HostNotFound,
ConnectionRefused, TimedOut (a timeout passed), ConnectionReset,
UnexpectedEof (the server closed before the end of the head),
Unsupported (a platform without sockets). The TLS errors are
tls.TlsError values: UnknownCa (the certificate doesn’t
chain to a trusted root), NameMismatch, CertificateExpired,
PeerAlert (the server refused), Truncated, and the others tls lists.
Over TLS, a body that ends with the connection must end with the server’s
close_notify: a plain TCP close is Tls { Truncated } there (someone
may have cut the connection). A body whose length is known
(Content-Length, chunked) is complete without it, as many servers skip
close_notify.
ProtocolError | When |
|---|---|
BadUrl | the URL is malformed |
UnsupportedScheme | not http or https |
BadStatusLine | not HTTP/1.x and a status from 100 to 599 |
BadHeader | a malformed or folded header line, or a transfer coding other than chunked |
HeadTooLarge | the head (interim responses included), or a chunked body’s trailers, over max_head |
BadContentLength | not a decimal number, or several that differ |
BadChunk | a chunk size that isn’t 1 to 15 hex digits, no CRLF after a chunk, a chunk line over max_head |
BodyTooLarge | the body over max_body (a Content-Length over it is refused before reading) |
TooManyRedirects, BadRedirect, InsecureRedirect | see Redirects |
TruncatedBody | the connection ended before the length or the last chunk said it would |
BadRequestLine | a server: not method SP target SP HTTP/x.y |
UnsupportedVersion | a server: a request in an HTTP version other than 1.0 and 1.1 |
BadTransferEncoding | a server: a request’s transfer coding other than one chunked |
BadExpect | a server: an Expect other than 100-continue |
BadRange | parse_range: several ranges, another unit, a malformed range |
A server connection uses BadHeader,
HeadTooLarge, BadContentLength, BadChunk, BodyTooLarge and
TruncatedBody for the request the way the client uses them for the
response.
Over HTTP/2 (a Client’s https requests), the response’s own failures
are H2 { e }, an h2.H2Error: the RFC 9113 error codes the server
resets a stream or ends the connection with (Protocol, Internal,
FlowControl, Refused, Cancel, Compression, Calm, …), and
Closed (the connection ended before the response), GoAway,
HeadTooLarge (over max_head), BodyTooLarge (over max_body) and
Malformed (a response that breaks HTTP/2’s rules).
let r: http.Response = http.get(url, opts) or {
match (err) {
http.HttpError.Io { e } => {
if (e == io.IoError.TimedOut) { io.eprintln("the server is too slow"); }
}
http.HttpError.Tls { e } => { io.eprintln("TLS: {e}"); }
http.HttpError.Http { e } => { io.eprintln("bad answer: {e}"); }
http.HttpError.H2 { e } => { io.eprintln("HTTP/2: {e}"); }
}
return 1;
};Server connections
A Server is the server half of HTTP/1.1 for one connection. It never
touches a socket or a clock: your loop gives it the bytes the socket
received (feed), sends the bytes it queues (output, advance_output)
and asks it what happened (phase, request). The same engine serves a
blocking loop, a net.Poller loop over thousands of connections, or bytes
in memory in a test. Bodies stream through its buffers in both
directions, so an upload of any size goes through without being held
whole.
// One connection, served to its end: blocking reads, one request at a time
fn serve(sock: net.TcpStream) {
var s: http.Server = http.server(http.server_options());
defer s.free();
var pending: str.Builder = str.builder(); // received, not yet taken by feed
defer pending.free();
var buf: [16384]u8;
var body: [4096]u8;
while (s.phase() != http.ServerState.Closing) {
if (pending.len() == 0) {
let n: i64 = sock.read(buf[0..16384]) or { 0 };
if (n == 0) { s.end_of_input(); } else { pending.append(buf[0..n]); }
}
let took: i64 = s.feed(pending.as_view()) or { 0 }; // an error: its answer is queued, Closing
let rest: string = "{pending.as_view()[took..pending.len()]}";
pending.clear();
pending.append(rest);
if (s.phase() == http.ServerState.Body) {
let r: *const http.RequestHead = s.request()!;
if (r.expect_continue) { s.continue_100(); }
while (s.read_body(body[0..4096]) > 0) {} // a real handler uses the bytes
}
if (s.phase() == http.ServerState.Response) {
let text: []const u8 = "hello\n";
s.respond(200, [http.Field { name: "Content-Type"; value: "text/plain"; }], text.len, time.unix_nanos() / 1000000000);
s.write_body(text);
s.end_body();
}
let out: []const u8 = s.output();
if (out.len > 0) {
sock.write_all(out) or { return; };
s.advance_output(out.len);
}
}
}pub struct ServerOptions {
max_head: i64; // request line and headers, bytes (16 KiB)
max_fields: i64; // header fields (100)
max_body: ?i64; // null: unlimited (a proxy streams); a limit answers 413
buffer: i64; // the body buffer, bytes (64 KiB): how much feed takes ahead of read_body
}
pub struct RequestHead {
method: []const u8; // the token as sent
target: []const u8; // path and query as sent; "*" for OPTIONS *; an absolute URI as sent
version: u8; // 10 or 11
head: []const u8; // the request line and header lines, CR LF line ends
content_length: ?i64; // the declared length; null when chunked or absent
chunked: bool; // Transfer-Encoding: chunked
has_body: bool; // content_length > 0 or chunked
keep_alive: bool; // the connection stays open after this exchange (unless you close it)
expect_continue: bool; // Expect: 100-continue
upgrade: bool; // Connection: upgrade with an Upgrade header
}
pub enum ServerState : u8 {
Head = 0; // reading a request head
Body = 1; // a head is available; its body streams through read_body
Response = 2; // the body is consumed; you write the response
Tunnel = 3; // after a 101: raw bytes both ways
Closing = 4; // send output, then close
}| Function | Does |
|---|---|
server_options() -> ServerOptions | The defaults above, to change field by field |
server(opts) -> Server | An engine waiting for a request, its buffers on the heap |
s.free() | Give the buffers back |
s.reset() | Make the engine ready for a new connection, as server() makes one with the same options, keeping its buffers: a server keeps one engine per connection slot and resets it instead of freeing and allocating three buffers per connection. The buffers are not cleared; the engine reads only what it is fed after the reset |
s.feed(data) -> i64 | Take received bytes; returns how many it took |
s.end_of_input() | The peer closed its side |
s.output() -> []const u8 | The bytes waiting to be sent |
s.advance_output(n) | n of them were sent |
s.phase() -> ServerState | Where the connection is |
s.request() -> ?*const RequestHead | The current request, from Body until the response ends |
r.header(name) -> ?[]const u8, r.headers() -> HeaderIter | Its headers, as Response has them |
s.read_body(dst) -> i64 | Body bytes, the framing removed; 0 when none are buffered now or the body ended |
s.body_done() -> bool | The whole body was read |
s.continue_100() | Queue HTTP/1.1 100 Continue, once |
s.respond(status, headers, body_len, now_unix) | Write the response head |
s.write_body(data) -> i64 | Body bytes into the output; returns how many it took |
s.end_body() | The response is complete |
s.close_after() | This response is the connection’s last |
s.read_raw(dst) -> i64, s.write_raw(data) -> i64 | A tunnel’s bytes, after a 101 |
A Server is not copied (a copy would share the buffers). Make one per
connection and free it when the connection is done.
The exchange
feed parses the request head. In Body you read request() and drain
the body with read_body until body_done(); chunked framing and
Content-Length are removed, trailers dropped. The phase moves to
Response once the whole body was read, or at once for a request without
one. Then respond, write_body as often as you need, and end_body;
the engine goes back to Head for the next request on the connection, or
to Closing.
request() and every field of the head are views into the engine’s head
buffer, valid until the next head begins (your end_body). Copy what you
keep longer.
Back pressure. feed takes at most what its buffers hold and returns
how many bytes it took: none past the end of the current request
(pipelined requests wait until the response’s end_body) and none while
you write a response. Keep the rest and offer it again after the next
read_body or end_body; stop reading the socket meanwhile. In the other
direction write_body takes what fits in the output and returns how much:
send output() and offer the rest again. Nothing grows without bound: the
output buffer grows only when a response head (or the engine’s own short
lines, the last chunk, 100 Continue) doesn’t fit beside what is still
unsent.
Responses
respond(status, headers, body_len, now_unix) writes:
- the status line,
HTTP/1.1 404 Not Found, with the reason phrase of RFC 9110 for the codes it names (HTTP/1.1 431with an empty one otherwise); Date, fromnow_unix(seconds since 1970, from your clock);- your headers, in order;
- the framing:
Content-Length: body_lenwhen you give a length;Transfer-Encoding: chunkedwhenbody_lenis null, eachwrite_bodybecoming a chunk (to an HTTP/1.0 client, a body to the connection’s end); nothing for a1xx,204,304or aHEADrequest, whosewrite_bodyis taken and dropped, so one handler servesGETandHEAD; Connection: closewhen the exchange ends the connection (the client asked,close_after, an HTTP/1.0 client without keep-alive, a body to the end), andConnection: keep-aliveto an HTTP/1.0 client that asked for it.
A 1xx other than 101 is an interim response (103 Early Hints): the
final one follows. Headers the engine writes itself trap if you give them
(Date, Content-Length, Transfer-Encoding, Connection): a proxy
relaying an origin’s head strips those four (and Keep-Alive) before
respond, and lets the engine frame the response for its own
connection. The same trap meets a
name that isn’t an HTTP token and a value with CR, LF or NUL. So do the
other mistakes a program could avoid: respond without a request or
twice, a status outside 100-599, write_body before respond or past the
Content-Length you gave, end_body before that many bytes were written.
You may answer before reading the body (a 401, a 413): the engine then
reads the rest of a Content-Length body and drops it before the next
request; a chunked body that hasn’t ended yet, or a 100-continue body
you refused, ends the connection after the response instead.
100-continue. A request with expect_continue and a body waits for
you: call continue_100() before reading the body when you want it, or
respond with a final status (417, 413, …) to refuse it.
read_body before either traps.
Upgrades. Answer a request with upgrade with 101 (giving your
Upgrade and Connection: upgrade headers, which the engine lets through
for a 101) and the engine is a Tunnel: read_raw gives what the peer
sends, write_raw queues to output, until end_of_input (Closing).
Errors
When a request is malformed, feed returns the ProtocolError and the
engine has already queued its answer, with Connection: close, and is
Closing: send output() and close the connection.
| Request | Error | Answer |
|---|---|---|
| a malformed request line | BadRequestLine | 400 |
| an HTTP version other than 1.0 and 1.1 | UnsupportedVersion | 505 |
a malformed or folded header line; no Host in HTTP/1.1, or two | BadHeader | 400 |
a bad Content-Length, or one beside Transfer-Encoding | BadContentLength | 400 |
a transfer coding other than chunked | BadTransferEncoding | 501 |
| a malformed chunk | BadChunk | 400 |
an Expect other than 100-continue | BadExpect | 417 |
the head over max_head or max_fields, trailers over max_head | HeadTooLarge | 431 |
the body over max_body | BodyTooLarge | 413 |
When the peer closes in the middle of a request, the next feed returns
TruncatedBody and the engine is Closing with nothing queued; a close
between requests is just Closing. Keep-alive is the request’s (HTTP/1.1
unless Connection: close, HTTP/1.0 only with Connection: keep-alive)
and close_after ends it either way; idle timeouts are your loop’s, with
its clock.
Client connections
A ClientConn is the client half of HTTP/1.1 for one connection, in the
same shape as a Server: you write a request into it (request,
write_body, end_body), send the bytes it queues (output,
advance_output), give it what the socket received (feed) and read the
response (response, read_body). It never touches a socket or a clock,
so one net.Poller loop can drive both sides of a proxy and keep its
connections to the origin open for the next request. Bodies stream through
its buffers in both directions. For plain blocking requests, get,
request and a Client are simpler.
A proxy holds a Server for the client’s socket and a ClientConn for
the origin’s, and its loop is one shape: feed each engine what its
socket gave, pump the request body from Server.read_body into
ClientConn.write_body and the response body the other way while either
side takes bytes, flush each engine’s output to its socket, and repeat
while something moved (a bound of a few dozen rounds guards against a
pathological ping-pong); then wait on the poller for the next readiness.
Check response() and body_done() to see where an exchange stands, not
only the phase: a response without a body goes from Head straight to
Idle.
// Two requests over one kept connection: blocking reads
fn fetch_two(sock: net.TcpStream) {
var c: http.ClientConn = http.client_conn(http.server_options());
defer c.free();
var pending: str.Builder = str.builder(); // received, not yet taken by feed
defer pending.free();
var buf: [16384]u8;
let paths: [2][]const u8 = ["/a", "/b"];
for (i in 0..2) {
if (c.phase() != http.ClientState.Idle) { return; } // the server closed it
c.request("GET", paths[i], [http.Field { name: "Host"; value: "example.com"; }], 0);
sock.write_all(c.output()) or { return; };
c.advance_output(c.output().len);
while (!c.body_done() && c.phase() != http.ClientState.Closing) {
if (pending.len() == 0) {
let n: i64 = sock.read(buf[0..16384]) or { 0 };
if (n == 0) { c.end_of_input(); } else { pending.append(buf[0..n]); }
}
let took: i64 = c.feed(pending.as_view()) or {
io.eprintln("bad response: {err.desc()}");
return;
};
let rest: string = "{pending.as_view()[took..pending.len()]}";
pending.clear();
pending.append(rest);
while (true) {
let k: i64 = c.read_body(buf[0..16384]);
if (k == 0) { break; }
io.print(buf[0..k]); // the body, as it comes
}
}
if (c.response() != null) { io.println("{paths[i]}: {c.response()!.status}"); }
}
}pub struct ResponseHead {
status: i64;
head: []const u8; // status line and header lines as received
content_length: ?i64; // the length framing the body; null when chunked, to the close, or no body
chunked: bool; // Transfer-Encoding: chunked
has_body: bool; // false for 1xx, 204, 304, a HEAD request, or Content-Length: 0
keep_alive: bool; // the connection stays usable after this exchange
upgrade: bool; // a 101
}
pub enum ClientState : u8 {
Idle = 0; // ready for a request (fresh, or kept after the last one)
Request = 1; // the head is written; you write the body
Head = 2; // the request is sent; waiting for the response head
Body = 3; // a head is here; its body streams through read_body
Tunnel = 4; // after a 101: raw bytes both ways
Closing = 5; // no further request: send output, then close
}| Function | Does |
|---|---|
client_conn(opts) -> ClientConn | An engine ready for its first request, with a ServerOptions’ limits, its buffers on the heap |
c.free() | Give the buffers back |
c.reset() | Ready for a new connection with the buffers kept, as s.reset() |
c.request(method, target, headers, body_len) | Write the request head |
c.write_body(data) -> i64 | Body bytes into the output; returns how many it took |
c.end_body() | The request is complete |
c.close_after() | This exchange is the connection’s last |
c.output() -> []const u8 | The bytes waiting to be sent |
c.advance_output(n) | n of them were sent |
c.feed(data) -> i64 | Take received bytes; returns how many it took |
c.end_of_input() | The peer closed its side |
c.phase() -> ClientState | Where the connection is |
c.response() -> ?*const ResponseHead | The response’s head, from its arrival until the next request |
h.header(name) -> ?[]const u8, h.headers() -> HeaderIter | Its headers, as Response has them |
c.read_body(dst) -> i64 | Body bytes, the framing removed; 0 when none are buffered now or the body ended |
c.body_done() -> bool | The whole body was read |
c.can_reuse() -> bool | Idle after an exchange that kept the connection |
c.read_raw(dst) -> i64, c.write_raw(data) -> i64 | A tunnel’s bytes, after a 101 |
A ClientConn is not copied (a copy would share the buffers). Make one
per connection and free it when the connection is done.
Requests
request(method, target, headers, body_len) writes method target HTTP/1.1, your headers in order (you give Host), and the framing:
Content-Length: body_lenwhen you give a length, and you write that many bytes withwrite_bodybeforeend_body;Transfer-Encoding: chunkedwhenbody_lenis null, eachwrite_bodybecoming a chunk andend_bodywriting the last one;- a
body_lenof 0 sends no body and the request is complete at once (noend_body):Content-Length: 0is written forPOST,PUTandPATCH, nothing for other methods; Connection: closewhen you calledclose_afterbefore, andConnection: upgradewhen your headers includeUpgrade.
The method and the target go out as you give them (a proxy forwards
methods it doesn’t know). An Expect header is not sent: 100-continue
isn’t supported, the body goes as it comes. Content-Length,
Transfer-Encoding and Connection are the engine’s to write and trap if
you give them, as do a name that isn’t an HTTP token, a value with CR, LF
or NUL, a method that isn’t a token, an empty target or one with spaces,
control characters or bytes above 127, request when the connection
isn’t Idle, write_body past the length you gave, end_body before
it and end_body after a request without a body.
Responses
feed parses the status line and the headers into a ResponseHead, then
the body: framed by Transfer-Encoding: chunked, by Content-Length, or
by the connection’s end (then keep_alive is false and body_done comes
after end_of_input). A 1xx, 204 and 304 have no body, nor does
the response to a HEAD request, whatever their headers say. Interim
responses (100 Continue, 103 Early Hints) are consumed and never
shown. Chunk extensions are ignored and trailers dropped.
The phase follows the exchange: Request while you write the body,
Head until the response head is in, Body while its body streams, then
Idle when the connection is kept (can_reuse() is true: your pool keeps
it for the next request to that origin, or closes it) or Closing. A
response without a body goes from Head straight to Idle or
Closing. A server may answer before your body is all sent (a 413, a
401): response() and read_body work at once, the phase stays
Request until your end_body.
keep_alive is HTTP/1.1 unless the response says Connection: close or
you called close_after; HTTP/1.0 only with Connection: keep-alive;
never for a body delimited by the connection’s end. response() and
every field of the head are views into the engine’s buffer, valid until
the next request.
Back pressure is the Server’s: feed takes at most what its buffers
hold and returns how many bytes it took, none past the end of the response;
keep the rest and offer it again after read_body. write_body takes
what fits in the output: send output() and offer the rest again.
Upgrades. A request with an Upgrade header answered with 101 puts
the engine in Tunnel: read_raw gives what the server sends (the bytes
that came right after the 101 first), write_raw queues to output,
until end_of_input (Closing).
Errors
A malformed response makes feed return the error once; the engine is
then Closing and drops what it is given. They are the errors of
http.get: BadStatusLine (also for bytes that arrive with no request
outstanding, and a 101 you didn’t ask for), BadHeader (and a transfer
coding other than chunked), HeadTooLarge (the heads together over
max_head, more than max_fields header lines, trailers over
max_head), BadContentLength, BadChunk, BodyTooLarge (over
max_body; a Content-Length above it is refused before the body) and
TruncatedBody, which the next feed returns when the peer closed before
the response was whole, or before any response came.
Caching helpers
pub struct ByteRange { first: i64; last: i64; } // inclusive| Function | Does |
|---|---|
parse_range(value, size) -> ?ByteRange | One Range: bytes= range resolved against size; null when it can’t be satisfied (answer 416) |
etag_matches(list, etag, weak_ok) -> bool | Does an If-Match or If-None-Match value match etag? |
format_http_date(unix) -> string | Seconds since 1970 as an HTTP date, Sun, 06 Nov 1994 08:49:37 GMT |
parse_http_date(text) -> i64 | An HTTP date as seconds since 1970 |
parse_range understands first-last, first- and -suffix; a last
past the end is clamped to size - 1. Several ranges, another unit, or a
range that isn’t one is BadRange: answer the whole representation
instead.
Range | size 1000 |
|---|---|
bytes=0-499 | 0-499 |
bytes=500- | 500-999 |
bytes=-100 | 900-999 |
bytes=900-5000 | 900-999 |
bytes=1000- | null (416) |
bytes=0-1,5-6 | BadRange |
etag_matches compares as RFC 9110 says for conditional requests: *
matches anything; otherwise any tag of the comma-separated list must be
the same tag, compared strongly (neither may be weak, W/"...") unless
weak_ok, which compares the quoted parts only (what If-None-Match
uses).
let inm: ?[]const u8 = r.header("If-None-Match");
if (inm != null && http.etag_matches(inm!, "\"v42\"", true)) {
s.respond(304, [http.Field { name: "ETag"; value: "\"v42\""; }], null, now);
s.end_body();
}parse_http_date reads the three forms HTTP has: Sun, 06 Nov 1994 08:49:37 GMT, the obsolete Sunday, 06-Nov-94 08:49:37 GMT (a two-digit
year is 1970-2069) and Sun Nov 6 08:49:37 1994; anything else is
BadHeader. format_http_date writes the first; years 0000 to 9999 (it
traps outside them).
Example
stdlib/examples/http_get.tape is a small wget: it fetches the URL
given on its command line, following up to five redirects, and prints the
status, the final URL and the body.
tape run stdlib/examples/http_get.tape -I stdlib -- http://127.0.0.1:8080/stdlib/examples/https_get.tape does the same over https, with the
bundled roots, a root of your own (--ca root.pem, PEM or DER), or the
operating system’s roots besides the bundled ones (--system):
tape run stdlib/examples/https_get.tape -I stdlib -- https://example.com/
tape run stdlib/examples/https_get.tape -I stdlib -- https://intranet.example/ --ca corp-root.pemLast modified: