Skip to content

HTTP

Make buffered or streaming HTTP requests, serve connections, and speak WebSocket.

Every HTTP operation is a host call: it suspends, and it returns Result[T, http.Error]. http is a module — import http — and its free functions are the stateless entry point; http.Client, http.BodyStream, http.Upload, http.Listener, http.Conn, and WebSocket are opaque host resources that release themselves through Drop.

http.Headers, http.Trust and http.Proxy are not resources — they are values a program builds and names. A Headers is a block of bytes; a Trust and a Proxy are handles on configuration the host read once and keeps for the store, so nothing releases them and building the same one twice answers the same handle.

A request

import http

fn fetch_status(url string) int ! http.Error {
    resp := http.get(url)?
    println("${resp.status} from ${resp.url}, ${resp.body.len()} bytes")
    return resp.status
}

fn main() void {
    match fetch_status("https://example.test/") {
        Ok(code) => println("got ${code}")
        Err(ConnectionRefused { url }) => println("refused by ${url}")
        Err(DnsError { host, message }) => println("dns ${host}: ${message}")
        Err(e) => println("transport failure")
    }
}

http.Error covers transport failures: ConnectionRefused, ConnectionTimeout, RequestTimeout, DnsError, TlsError, InvalidUrl, TooManyRedirects and NetworkError; a WebSocket peer’s goodbye, Closed; and what the server half refuses with, each its own variant: InvalidHeader, HeaderRefused, NotOpen, Busy, PeerClosed, BadStatus, NoRequest, BodyTooLarge and RouteRejected, which says why in a RouteFault. Other is the failure with no kind of its own.

The two timeouts are separate questions and answer separately. ConnectionTimeout is the connection never coming up; RequestTimeout is the exchange not finishing. Each carries the duration_ms it was given.

How long a request may take

Every verb takes a timeout after its required arguments: how long the whole exchange may take, head and body, as a time.Duration. Left out, it is None and the transport’s own bound applies.

import http
import time

fn poll_quickly() int {
    return match http.get("https://example.test/health", time.Duration.of_seconds(2)) {
        Ok(r) => r.status
        Err(RequestTimeout { url, duration_ms }) => -duration_ms
        Err(e) => -1
    }
}

The other bound — how long bringing the connection up may take — is a property of the connection pool rather than of one request, so it lives on Client:

import http
import time

fn ask_a_slow_host() int {
    // Base URL, then the request bound, then the connect bound.
    c := http.client(
        "https://example.test",
        time.Duration.of_seconds(5),
        time.Duration.of_millis(750)
    )
    return match c.get("/report") {
        Ok(r) => r.status
        Err(ConnectionTimeout { url, duration_ms }) => -1
        Err(e) => -2
    }
}

None — the default for both — takes the transport’s own loose backstop, thirty seconds to connect and five minutes for a whole request, which exists so that nothing waits forever. A bound under a millisecond is a millisecond, so a bound you stated is never read as the default.

A third bound is time.push_deadline, which the scheduler enforces from outside on everything the task does. Use it for “this whole piece of work has two seconds”; use timeout for “this request has two seconds”.

A timeout that fires on a bound you stated reports that number back. One that fires on an ambient deadline reports duration_ms: 0, because the bound was the guest’s own and the transport is told only that it passed.

InvalidUrl means the bytes are not a URL. It is not what a peer that accepted and hung up produces — that is NetworkError, carrying the transport’s own words — so a program validating user-supplied URLs can branch on InvalidUrl without rejecting good ones because a far server crashed.

import http

error ApiError { NotFound, Rejected { status: int }, Transport }

fn read_user(url string) string ! ApiError {
    resp := match http.get(url) {
        Ok(r) => r
        Err(e) => error Transport
    }
    if resp.status == 404 {
        error NotFound
    }
    if resp.status >= 400 {
        error Rejected { status: resp.status }
    }
    return string.from_utf8(resp.body).ok() ?? ""
}

fn main() void {
    match read_user("https://api.example.test/users/1") {
        Ok(body) => println("${body.len()} chars")
        Err(NotFound) => println("no such user")
        Err(Rejected { status }) => println("server said ${status}")
        Err(Transport) => println("could not reach the server")
    }
}

Body bytes are never implicitly decoded. string.from_utf8(body) returns a Result, so an invalid-UTF-8 body is an error you must handle (.ok() is the Option) rather than a silent mojibake.

Verbs and bodies

Call Body argument
http.get(url) —
http.post(url, body) []byte
http.put(url, body) []byte
http.delete(url) —
http.head(url) — (response has no body)
http.get_stream(url) — (returns http.BodyStream)

Request bodies are owned []byte. string.to_bytes() produces exactly that; string.bytes() is a lazy iterator over the bytes, not a list, and will not type-check here until .collect() builds one.

import http

fn publish(url string, json string) int ! http.Error {
    created := http.post(url.clone(), json.to_bytes())?
    replaced := http.put(url.clone(), json.to_bytes())?
    probed := http.head(url.clone())?
    removed := http.delete(url)?
    return created.status + replaced.status + probed.status + removed.status
}

fn main() void {
    match publish("https://api.example.test/items/1", "{\"n\":1}") {
        Ok(total) => println("status total ${total}")
        Err(e) => println("failed")
    }
}

Response headers

resp.headers is a Headers: every header the server sent, in the order it sent them, with the names lower-cased. It is read once when the response is assembled, and a lookup walks it and parses nothing. has_header(name) is a case-insensitive presence test, and resp.headers.entries() is every header as a Header { name, value }.

import http

fn describe(url string) string ! http.Error {
    resp := http.get(url)?
    if !resp.has_header("content-type") {
        return "untyped response"
    }
    return "${resp.headers.len()} headers"
}

fn main() void {
    match describe("https://example.test/") {
        Ok(line) => println(line)
        Err(e) => println("failed")
    }
}

header(name) reads one value out and header_at(name, index) reaches a repeated one — Set-Cookie is always repeated. Both answer None for a header that was not sent, which is a different fact from one sent empty.

import http

fn kind(url string) string ! http.Error {
    resp := http.get(url)?
    return match resp.header("content-type") {
        Some(v) => v
        None => "untyped"
    }
}

fn main() void {
    match kind("https://example.test/") {
        Ok(line) => println(line)
        Err(e) => println("failed")
    }
}

Names are matched without regard to ASCII case: the names are kept lower-cased, and a lookup compares the name it is given with each of them without building anything.

resp.url is the final URL, which differs from the requested one after a redirect. Anything that authorizes on host or path must read resp.url, not the string it passed in.

Request headers

http.headers() builds a set to add to, and http.request is the general verb that carries it. Client.request is the same thing against a base URL.

import http

fn authorized(url string, token string) int ! http.Error {
    mut h := http.headers()
    h.add("authorization", "Bearer ${token}")?
    h.add("content-type", "application/json")?
    resp := http.request(http.Method.Post, url, "{}".to_bytes(), h)?
    return resp.status
}

fn main() void {
    match authorized("https://api.example.test/v1/things", "secret") {
        Ok(code) => println("${code}")
        Err(e) => println("request failed")
    }
}

A name added twice sends the header twice, which is what HTTP means by a repeated header; there is no set that replaces one. add refuses a name or a value that would end its header and start another, an empty name, and a name with a colon, with InvalidHeader naming the header, and leaves the set as it was. The wire refuses the rest when the request is sent: a name that is not a token, a value with a control byte, and the four framing headers (HeaderRefused).

Who you trust

https:// and wss:// verify against a compiled-in root program — Mozilla’s, the same set every browser ships — and a certificate it does not vouch for is refused rather than downgraded. For an internal service behind a private CA, or for mutual TLS, build a Trust and name it.

import http

fn internal(base string, ca string) int ! http.Error {
    t := http.trust(ca)?
    client := http.client(base).trusting(t)
    resp := client.get("/health")?
    return resp.status
}

fn main() void {
    match internal("https://svc.internal", "/etc/pki/internal-ca.pem") {
        Ok(code) => println("${code}")
        Err(e) => println("unreachable")
    }
}
  • http.trust(ca_path) — verify against the certificates in that file.
  • http.identify(cert_path, key_path) — present a client certificate, verifying against the compiled-in roots.
  • http.trust_and_identify(ca, cert, key) — both.
  • http.WebSocket.connect_trusting(url, t) — the same profile, for wss://.

The paths are files, the same vocabulary Server.tls(cert, key) uses on the accept side, and they are read once: an identical ask answers the profile already built rather than reading again.

Named roots replace the compiled-in program, they do not add to it. A caller that says “trust this CA” and silently keeps the public ones has a weaker posture than it asked for; a caller that meant “and also” finds out at the first public host, loudly. Concatenating the two PEM files is how “and also” is spelled.

Trust keys the connection pool, so it lives on Client and not on a call: a connection is verified once, when it comes up, and a pooled one carries that verification into every later request on it. The module-level verbs — http.get, http.request — use the compiled-in roots.

Where connections go out

A proxy has always worked: the transport reads HTTP_PROXY, HTTPS_PROXY, ALL_PROXY and NO_PROXY from the environment, and that is what a client uses unless told otherwise. What a program can now do is say — route one client through a proxy and another directly, or refuse the environment’s answer.

import http

fn fetch_via(base string, relay string) int ! http.Error {
    p := http.proxy(relay, "localhost,127.0.0.1")?
    client := http.client(base).through(p)
    resp := client.get("/thing")?
    return resp.status
}

fn main() void {
    match fetch_via("http://example.test", "http://relay.internal:3128") {
        Ok(code) => println("${code}")
        Err(e) => println("failed")
    }
}

http.proxy(url, bypass) routes every scheme through url; bypass is a NO_PROXY-shaped list of hosts to reach directly anyway. http.no_proxy() is the other statement: ignore the environment and connect direct. Like trust, a routing keys the connection pool, so it lives on Client and not on a call.

Redirects

http.request takes redirects after timeout, and http.client takes it after the connect bound. It is a Redirects?: Some(Redirects.Never) follows none — a 3xx comes back as itself, Location readable rather than acted on — Some(Redirects.AtMost(n)) follows at most n, and None, the default, takes the transport’s own limit of ten, which is what every other verb uses.

import http

fn probe(url string) int ! http.Error {
    resp := http.request(
        http.Method.Get,
        url,
        List.new[byte](0),
        http.headers(),
        None,
        http.Redirects.Never
    )?
    return resp.status
}

fn main() void {
    match probe("https://example.test/maybe-elsewhere") {
        Ok(code) => println("${code}")
        Err(e) => println("probe failed")
    }
}

None is the transport’s own on every one of these — timeout, connect_timeout, redirects — so there is one convention rather than two. Not following is its own word, because it is a deliberate act and should read like one at the call site rather than arriving by a zero somebody left in a field.

The policy keys the connection pool rather than riding the request, the way the connect bound does: the transport underneath fixes it when it is built. Two clients that state the same one share the same sockets, and two that do not get one pool each.

A value carrying a newline is refused where it is written. That is response splitting and request smuggling, and by the time a header block reaches the host a newline inside a value has already become a second header — nothing over there can tell it from one you meant. So add judges its two arguments and answers Err(InvalidHeader { name }) when either fails, leaving the set as it was; nothing is marked, and nothing goes out that you did not write.

Four headers are the wire’s and are refused by the host: content-length, transfer-encoding, connection and upgrade. Framing is decided from the body the transport was handed, and a second author for it is a message that disagrees with itself.

Streaming a request body

Every verb above hands the host one block, so the whole body has to be in it. It is lent rather than copied — no allocation the size of the body — but a file bigger than the heap still cannot be sent that way.

http.upload opens the body instead. send_chunk writes one piece and parks until it is on the wire; finish ends the body and answers an ordinary Response.

import http

fn push(url string, parts []string) int ! http.Error {
    mut h := http.headers()
    h.add("content-type", "application/octet-stream")?
    up := http.upload(http.Method.Put, url, h)?
    mut sent := 0
    for p in parts {
        sent = sent + up.send_chunk(p.to_bytes())?
    }
    resp := up.finish()?
    if resp.status != 200 {
        return 0
    }
    return sent
}

fn main() void {
    match push("https://example.test/blob", ["one", "two"]) {
        Ok(n) => println("${n} bytes")
        Err(e) => println("upload failed")
    }
}

The body goes out Transfer-Encoding: chunked, with no declared length — which is the point: nothing had to know the total up front. Parking on each piece is the backpressure, so a slow peer slows the sender rather than growing a queue, and the block a piece came out of is free to reuse the moment send_chunk answers.

An Upload that is never finished releases its request when it drops, so an abandoned one does not hold a socket.

Reusable clients

http.client(base_url) builds a host-owned client with pooled connections and relative-path verbs. Use one client for many calls to the same service.

import http

fn sync(base string) int ! http.Error {
    client := http.client(base)
    profile := client.get("/v1/profile")?
    events := client.get("/v1/events")?
    client.post("/v1/ack", "{}".to_bytes())?
    client.put("/v1/profile", "{}".to_bytes())?
    client.delete("/v1/events/1")?
    return profile.status + events.status
}

fn main() void {
    match sync("https://api.example.test") {
        Ok(total) => println("${total}")
        Err(e) => println("sync failed")
    }
}

http.Client has get, post, put, delete, head, and request — the last for any method with headers on it. There is nothing to close: a Client is a base URL, and the connection pool underneath it is the one shared transport, not this value’s.

Streaming a response body

http.get_stream(url) suspends only until the response head arrives, then hands back an http.BodyStream. Each next() yields the next run of bytes; an empty chunk is end-of-body and is never real content.

The head is readable before the first chunk, and reading it first is the point: status(), header(name), headers() and url() all answer off the same exchange, so a download decides whether it wants the body before it pulls any of it.

import http

fn download_size(url string) int ! http.Error {
    body := http.get_stream(url)?

    // Decided on the head, before a single byte of body.
    if body.status() != 200 {
        body.close()
        return 0
    }
    mut total := 0
    for {
        chunk := body.next()?
        if chunk.is_empty() {
            break
        }
        total = total + chunk.len()
    }
    body.close()
    return total
}

fn main() void {
    match download_size("https://example.test/large.bin") {
        Ok(n) => println("${n} bytes streamed")
        Err(e) => println("download failed")
    }
}

Without that check the function counts a 404 body as the file and answers Ok(n). It is also where the resp.url() check belongs when the origin is not one you chose — see Redirects.

http.request_stream(method, url, body, headers) is the same opener with a method and headers on it, for a download that needs an Authorization or a Range. A method is an http.Method: Get, Head, Post, Put, Delete, Patch, Options, Connect, Trace, or Other("PROPFIND") for any other upper-case token. method.as_str() is its token and http.Method.parse(token) reads one. What protocol an exchange spoke is an http.HttpVersion (Http09 to Http3), None where the transport will not say.

next() hands every chunk on a block of its own. A loop that keeps one buffer and reads into it, body.next_into(&mut buf), appends the chunk and answers how many bytes it was (0 is the end), so a download allocates nothing per piece once the buffer has grown. header(name) finds one header in the head without building the set headers() answers; take headers() once for several.

A configured client streams too: client.get_stream(path), client.request_stream(...) and client.upload(...) carry that client’s connect bound, trust profile and routing, which the module-level functions cannot be told about. Those are the two request shapes that exist because the body does not fit in memory, so they are the two most likely to be pointed at a service behind a private CA or a proxy.

pump_into(stream) turns the body into a Stream[List[byte]] so it composes with select, race, and other streams. The caller owns the ring, so it chooses the capacity and can close it to abandon the download early; body.into_stream(capacity) is the same with a ring of its own. The pump applies backpressure: a fast body never outruns a slow consumer, and no chunk is dropped.

import http
import task

fn main() void {
    match http.get_stream("https://example.test/large.bin") {
        Ok(body) => {
            chunks := task.Stream.new[List[byte]](8)
            body.pump_into(chunks)
            mut total := 0
            mut draining := true
            for draining {
                match chunks.recv() {
                    Some(chunk) => total = total + chunk.len()
                    None => draining = false
                }
            }
            println("${total} bytes via stream")
        }
        Err(e) => println("could not open body")
    }
}

The adapter closes the destination at EOF, when the consumer abandons it, and after a mid-body transport error — so a truncated download reads as a clean end-of-stream. When integrity matters, drive next() directly: it surfaces each chunk’s Result precisely.

Streaming bounds memory only if the consumer actually releases chunks. Appending every chunk to one list is a buffered request with extra steps.

WebSocket clients

import http

fn subscribe(url string) string ! http.Error {
    socket := http.WebSocket.connect(url)?
    socket.send("subscribe")?
    socket.send_bytes("ping".to_bytes())?

    text := socket.receive()?
    binary := socket.receive_bytes()?
    println("${binary.len()} binary bytes")

    socket.close()
    return text
}

fn main() void {
    match subscribe("wss://events.example.test/socket") {
        Ok(msg) => println("first message: ${msg}")
        Err(e) => println("socket failed")
    }
}

send/receive carry text frames, send_bytes/receive_bytes carry binary ones. The surface exposes no ping, pong, or close-frame metadata, and close() releases the host halves without sending a close frame — send a graceful close yourself if the protocol demands one.

ws:// and wss:// are both dialled; a wss:// runs the same handshake over TLS, verified against the same compiled-in roots https:// uses. A certificate those roots do not vouch for is refused rather than downgraded — connect_trusting(url, t) is how a private CA or a client identity is named, with the Trust values above. A build compiled without the tls feature refuses wss:// by name.

Servers

http.listen(addr) binds a listener; accept() yields one http.Conn at a time. On a connection, request() reads and parses the whole request and respond(status, body) writes the reply.

The version is the socket’s, not the build’s: a listener serves HTTP/1.1 or HTTP/2 depending on what the client speaks, and the guest code below is the same either way.

import http

fn serve(addr string, rounds int) int ! http.Error {
    listener := http.listen(addr)?
    mut served := 0
    for i in 0..rounds {
        conn := listener.accept()?
        req := conn.request()?
        println("${req.method} ${req.url} (${req.body.len()} body bytes)")
        conn.respond(200, "ok\n".to_bytes())?
        conn.close()
        served = served + 1
    }
    listener.close()
    return served
}

fn main() void {
    match serve("127.0.0.1:8080", 4) {
        Ok(n) => println("served ${n} requests")
        Err(e) => println("listener failed")
    }
}

Describing a server

http.listen(addr) is a server with everything at its default. When it needs to be something else — TLS, a body bound, a handler deadline, CORS, compression — describe it first and bind it once:

import http
import time

fn start() Result[http.Listener, http.Error] {
    s := http.server("0.0.0.0:8443")
    s.tls("/etc/certs/site.pem", "/etc/certs/site.key")
    s.max_body(8 * 1024 * 1024)
    s.timeout(time.Duration.of_seconds(30))
    s.compress()
    s.cors("https://app.example.com")
    return s.listen()
}

fn main() void {
    match start() {
        Ok(l) => match l.port() {
            Ok(p) => println("listening on ${p}")
            Err(e) => println("bound, but the port could not be read")
        }
        Err(e) => println("the server could not start")
    }
}

Mutual TLS, the accept side

Client.trusting(t) names who a program will believe; Server.client_ca(ca) names who it will admit. A client that presents no certificate, or one that will not chain to those roots, is refused in the handshake and never becomes a request — so a handler never sees an unauthenticated caller and does not have to check for one.

import http

fn serve(l http.Listener) int {
    c := match l.accept() { Ok(c) => c Err(e) => return -1 }
    _ := match c.request() { Ok(r) => r Err(e) => return -2 }
    // Whoever got here proved this. What it is allowed to do is yours
    // to decide; whether to believe it is not.
    match c.respond(200, c.peer_names().join(",").to_bytes()) {
        Ok(w) => {}
        Err(e) => return -3
    }
    c.close()
    return 1
}

peer_names() answers the certificate’s subject alternative names as a list of strings — DNS names first, then URI names. It is empty when nobody proved anything, which is the truth in three cases a handler cannot tell apart and does not need to: a cleartext listener, a listener that asks for no certificate, and client_ca(ca, anonymous: true) — which still asks, still refuses a certificate it cannot chain, and admits a client that declined. Use that last one when a proven identity is extra authority rather than the price of entry.

The named roots are the whole set, exactly as http.trust is on the client side. A server that said “accept certificates from this CA” and quietly kept the public root program too would admit anything the world’s CAs will sign, which is the opposite of what mutual TLS is for.

Nothing touches the machine until listen(): tls records two paths and listen is what reads them, so a certificate that is missing or malformed fails where you asked for it rather than on the first handshake. The description is spent by listen — a second call on the same Server is an error, not a second socket.

Each knob is worth knowing the default of:

call default what it does
tls(cert, key) off Terminates TLS from a PEM pair. ALPN offers HTTP/2 first, then HTTP/1.1.
client_ca(ca, anonymous) off Requires a client certificate chaining to ca. Only meaningful beside tls.
authenticate(schemes) off Every operation of a served service needs a caller a scheme verified, except an @open one. See Authentication and roles.
grant(roles) none The program’s function granting a verified caller its roles, run once a credential.
max_body(bytes) 2 MiB Answers 413 above the bound. unbounded_body() removes it.
timeout(d) off Answers 408 when a handler takes longer than the time.Duration.
header_timeout(d) 30 s How long a connection may say nothing, handshake and request head included. no_header_timeout() removes it.
max_connections(n) unbounded The most connections open at once; further peers wait in the kernel’s backlog. unlimited_connections() removes the cap.
cors(origin) off Answers preflights and adds the headers. "*" admits any origin.
compress() off gzip, brotli, deflate or zstd, whichever the client offered.
shared() off SO_REUSEPORT, so one port can be held by several lanes.
http3() off Also answers QUIC on the same address. Needs tls.
shared() on both — SO_REUSEPORT applies to the UDP socket too, so HTTP/3 balances across lanes like HTTP/1.1 and HTTP/2.

http3() binds a QUIC endpoint on the same port number the TCP listener took — including when the description said :0 and the kernel picked it — and every answer the TCP half gives then carries an Alt-Svc header naming it. That header is how a browser discovers HTTP/3 at all: there is no DNS record and no port convention, so an endpoint nobody is told about serves no HTTP/3 traffic.

max_body is the one that is on unless you turn it off, and the asymmetry is deliberate: a missing deadline costs you a slow handler, while a missing body bound costs you the process. One small request declaring a gigabyte of body is enough to make a reader reserve a gigabyte, fail, and take every other connection down with it.

http.Request carries method (an http.Method), url, and body — request headers are not part of the record, because a whole header block in a guest block would cost every request what few requests read. conn.header(name) and conn.header_at(name, index) pull one out of hyper’s own parse instead; for a reader that has to walk all of them — a proxy, an access log — conn.headers() answers the whole set, a Headers like the client half’s resp.headers. Note the loop bound: ? on accept() tears the whole server down on one bad connection, which is almost never what a real server wants. See the worked example below.

Who connected

conn.peer_ip() and conn.peer_port() answer the address at the other end — the socket’s, which is what an access log and a rate limiter need. The address is a net.IpAddr, held by value. X-Forwarded-For and Forwarded are headers a client writes: read them with conn.header(name) when a trusted proxy is in front, and decide for yourself whether to believe them. Behind a proxy, peer_ip() is the proxy’s.

peer_ip() and peer_port() answer None for a connection whose peer the platform would not name, which for an accepted socket does not happen in practice. A v4 client of a dual-stack listener answers 127.0.0.1 and not ::ffff:127.0.0.1. On the client side, stream.peer() of a streaming exchange is the net.SocketAddr the request actually reached, which is what an allow-list after a name lookup has to check.

Response headers

respond_with(status, body, headers) is respond with headers on it, and respond_begin_with(status, headers) is the streaming half’s. Both take the same http.headers() set the client uses, under the same two rules: a value with a newline in it is refused where it is added, and the four framing headers are the wire’s.

import http

fn answer(conn http.Conn) int ! http.Error {
    _ := conn.request()?
    mut h := http.headers()
    h.add("content-type", "application/json")?
    h.add("cache-control", "no-store")?
    return conn.respond_with(200, "{\"ok\":true}".to_bytes(), h)?
}

fn main() void {
    match http.listen("127.0.0.1:8080") {
        Ok(listener) => match listener.accept() {
            Ok(conn) => match answer(conn) {
                Ok(n) => println("${n} bytes")
                Err(e) => println("answer failed")
            }
            Err(e) => println("accept failed")
        }
        Err(e) => println("bind failed")
    }
}

Without them every answer went out with a status, a length and nothing else — so a JSON API could not name its own type and nothing could set a cookie.

Streaming an inbound body

For uploads, request_head() parses only the request line and headers — the returned body is empty and the real body stays on the wire. receive_chunk() then pulls it piece by piece, with an empty piece marking end-of-body.

import http

fn absorb(conn http.Conn) int ! http.Error {
    head := conn.request_head()?
    println("${head.method} ${head.url}, buffered body = ${head.body.len()}")

    mut received := 0
    for {
        piece := conn.receive_chunk()?
        if piece.is_empty() {
            break
        }
        received = received + piece.len()
    }

    conn.respond(200, "stored\n".to_bytes())?
    return received
}

fn main() void {
    match http.listen("127.0.0.1:8080") {
        Ok(listener) => {
            match listener.accept() {
                Ok(conn) => match absorb(conn) {
                    Ok(n) => println("${n} bytes uploaded")
                    Err(e) => println("upload failed")
                }
                Err(e) => println("accept failed")
            }
        }
        Err(e) => println("bind failed")
    }
}

Drain to EOF (or close() the connection) before the next request_head() on a keep-alive connection. A receive_chunk() with no prior request_head(), or after the body drained, is a safe empty.

Streaming an outbound body

respond_begin(status) writes the status line with Transfer-Encoding: chunked, each send_chunk writes one frame, and respond_end() writes the terminator. Call them in that order.

import http

fn stream_reply(conn &http.Conn, parts &[]string) int ! http.Error

{
    conn.respond_begin(200)?
    mut sent := 0
    for p in parts {
        chunk := p.to_bytes()
        conn.send_chunk(chunk.clone())?
        sent = sent + chunk.len()
    }
    conn.respond_end()?
    return sent
}

fn main() void {
    mut parts: []string = List.new[string]()
    parts.push("alpha\n")
    parts.push("beta\n")

    match http.listen("127.0.0.1:8080") {
        Ok(listener) => {
            match listener.accept() {
                Ok(conn) => match stream_reply(conn, parts) {
                    Ok(n) => println("streamed ${n} bytes")
                    Err(e) => println("stream failed")
                }
                Err(e) => println("accept failed")
            }
        }
        Err(e) => println("bind failed")
    }
}

An empty send_chunk is a no-op on purpose: an empty data frame would encode the terminator and end the response early. Signal end-of-body only with respond_end().

Upgrading to a WebSocket

conn.upgrade_websocket() reads the Upgrade: websocket request, writes 101 Switching Protocols, and takes owned possession of the socket. On success the http.Conn is consumed — its handle is dead, and you use the returned WebSocket. On failure the connection is untouched and still usable for an ordinary respond.

import http

fn echo_socket(conn http.Conn, rounds int) int {
    socket := match conn.upgrade_websocket() {
        Ok(s) => s
        Err(e) => {
            match conn.respond(400, "not a websocket\n".to_bytes()) {
                Ok(_) => {}
                Err(e2) => {}
            }
            return 0
        }
    }

    mut echoed := 0
    for i in 0..rounds {
        msg := match socket.receive() {
            Ok(m) => m
            Err(e) => break
        }
        match socket.send("echo: ${msg}") {
            Ok(_) => { echoed = echoed + 1 }
            Err(e) => break
        }
    }
    socket.close()
    return echoed
}

fn main() void {
    match http.listen("127.0.0.1:8080") {
        Ok(listener) => {
            match listener.accept() {
                Ok(conn) => println("echoed ${echo_socket(conn, 8)} frames")
                Err(e) => println("accept failed")
            }
        }
        Err(e) => println("bind failed")
    }
}

A worked server

A real accept loop keeps running when one connection fails, routes on the request, and hands each connection to its own task so a slow client cannot block the listener.

import http

fn route(req http.Request) (int, string) {
    if req.url == "/health" {
        return (200, "ok")
    }
    if req.method.as_str() != "GET" {
        return (405, "method not allowed")
    }
    return (404, "not found")
}

fn handle(conn http.Conn) int {
    req := match conn.request() {
        Ok(r) => r
        Err(e) => {
            conn.close()
            return 0
        }
    }

    status, text := route(req)
    match conn.respond(status, text.to_bytes()) {
        Ok(_) => {}
        Err(e) => println("could not write response")
    }
    conn.close()
    return status
}

fn main() void {
    listener := match http.listen("127.0.0.1:8080") {
        Ok(l) => l
        Err(InvalidUrl { url }) => {
            println("bad bind address: ${url}")
            return
        }
        Err(e) => {
            println("bind failed")
            return
        }
    }

    for i in 0..16 {
        match listener.accept() {
            Ok(conn) => {
                worker := spawn { handle(conn) }
                // `detach()` is not optional here. `spawn` answers a
                // `Task`, and dropping a task handle CANCELS the task,
                // subtree-deep. Without this line `worker` dies at the
                // end of the iteration and takes the connection with
                // it -- killed at its first suspension point, before
                // `handle` has read a single byte. Detaching severs the
                // task from the structured tree; run teardown still
                // cancels it like any other.
                worker.detach()
                println("connection ${i} dispatched")
            }
            Err(e) => {
                println("accept failed; stopping")
                break
            }
        }
    }
    listener.close()
}

Cancellation and connection limits are application policy — the stdlib gives you the loop and the resources, not the shape of the server. That policy starts with what you do with the Task each spawn answers: detach it and the connection outlives the loop iteration, hold it (in a List[task.Task[int]], say) and you can bound concurrency and reap results, drop it and you have cancelled the connection you just accepted. There is no fourth option, and the third one is silent. (Per-request timeouts on the client side are timeout, above.)

Resource lifetimes

Every listener, connection, client, body stream, and socket is a scoped host resource with a Drop impl. An ordinary return, a break, or a propagated ? still releases it. close() is synchronous (it adds no suspension point) and idempotent; call it when the resource must go before the end of a long-lived scope.

Effects

Everything that waits on the network carries Suspend, and callers inherit it by inference; fallible wrappers also carry Error. Neither is written down, and the compiler says nothing about either unless a function declares a row with using [...]. Closing is synchronous, so cleanup runs during ordinary scope exit without a new suspension point.

See Suspension for the effect boundary and Streams for backpressure semantics.

Security

Transport success says nothing about content trust. For requests derived from user input:

  • restrict schemes and destinations so a URL cannot reach the internal network;
  • account for redirects — resp.url can differ from the requested URL, and Redirects.Never stops the transport chasing one past a URL you checked;
  • validate status, media type, size, and decoding before parsing;
  • do not reflect raw remote messages into trusted logs or responses;
  • use https/wss when confidentiality and peer authentication matter.

Buffered helpers materialize the whole body in guest memory, up to the 16 MiB a Client buffers unless limited(n) or unbounded() says otherwise — bound the time with timeout and the bytes with get_stream, which hands the body over in pieces you decide whether to keep. The host performs DNS and TLS, so certificate roots, proxy behavior and destination allow-lists are deployment policy. A typed response record does not replace those controls.

Type to search…

↑↓ navigate↵ selectEsc close