Skip to content

std::http

An HTTP client and server. A Request is a value; http.fetch sends it with the ambient client and reads the whole response, and http.stream returns a StreamedResponse, its body still arriving, for defer StreamedResponse.close(response) to close. A status is never an error: a 404 is a Response whose status a program checks with Status.is_success.

response = http.get(Url"https://api.example.com/users")?

if Status.is_success(response.status) then dbg Response.text(response)?

Every request runs under the context in force: its deadline bounds the request, and cancelling the task cancels it. std::http::testing.run serves requests with a function instead of the network, in tests and in the tour. A Client made with Client.new holds its own options and connection pool.

A server never reads more of a request’s body than a limit allows. Request.form and post_form read at most 10 MB of a URL-encoded body (Go’s ParseForm limit), and multipart_form and form_file at most 32 MB of a multipart one; they stop one byte past the limit and return Error.BodyTooLarge. A limit on the request replaces both defaults, up or down: Request.limit_body or the http.limit_body middleware for a route, and the Server’s max_body for every request. Limits on one request only lower each other, so a route cannot pass the server’s. Request.text and json_as read a body whole under the same limit as a URL-encoded form. Body.read_all and Body.reader read what the stream holds, stopped only by such a limit.

Import with import std::http.

A middleware takes a handler first and returns a handler, so a stack of them reads as a pipe, each stage wrapping the ones before it: Router.handler(router) |> http.limit_body(1_000_000). wrap_routes wraps only a group of routes, such as every /admin route.

enum Method
    Get
    Head
    Post
    Put
    Patch
    Delete
    Connect
    Options
    Trace
    Other String
end

A request method. Other holds any method Go sends as written.

fn text(method: Method) -> String

type function on Method

The method as it is written on the wire: GET, or Other’s text.

import std::http.Method

assert Method.text(Method.Patch) == "PATCH"
assert Method.text(Method.Other("PURGE")) == "PURGE"
fn parse(text: String) -> Method

type function on Method

The method text names, Other for one Go has no constant for.

import std::http.Method

assert Method.parse("DELETE") == Method.Delete
assert Method.parse("PURGE") == Method.Other("PURGE")

impl Display for Method

fn to_string(method: Method) -> String

impl Display.to_string

impl Debug for Method

fn inspect(value: Method) -> String

impl Debug.inspect

impl Equatable for Method

fn equal(a: Method, b: Method) -> Bool

impl Equatable.equal

impl Hashable for Method

fn hash(value: Method) -> Int

impl Hashable.hash

type Status Int

An HTTP status code. Any code from 100 to 999 is a Status; the constants name the ones Go names.

once continue_status: Status
once switching_protocols: Status
once processing: Status
once early_hints: Status
once ok: Status
once created: Status
once accepted: Status
once non_authoritative_info: Status
once no_content: Status
once reset_content: Status
once partial_content: Status
once multi_status: Status
once already_reported: Status
once im_used: Status
once multiple_choices: Status
once moved_permanently: Status
once found: Status
once see_other: Status
once not_modified: Status
once use_proxy: Status
once temporary_redirect: Status
once permanent_redirect: Status
once bad_request: Status
once unauthorized: Status
once payment_required: Status
once forbidden: Status
once not_found: Status
once method_not_allowed: Status
once not_acceptable: Status
once proxy_auth_required: Status
once request_timeout: Status
once conflict: Status
once gone: Status
once length_required: Status
once precondition_failed: Status
once request_entity_too_large: Status
once request_uri_too_long: Status
once unsupported_media_type: Status
once requested_range_not_satisfiable: Status
once expectation_failed: Status
once teapot: Status
once misdirected_request: Status
once unprocessable_entity: Status
once locked: Status
once failed_dependency: Status
once too_early: Status
once upgrade_required: Status
once precondition_required: Status
once too_many_requests: Status
once request_header_fields_too_large: Status
once unavailable_for_legal_reasons: Status
once internal_server_error: Status
once not_implemented: Status
once bad_gateway: Status
once service_unavailable: Status
once gateway_timeout: Status
once http_version_not_supported: Status
once variant_also_negotiates: Status
once insufficient_storage: Status
once loop_detected: Status
once not_extended: Status
once network_authentication_required: Status
fn from_code(code: Int) -> Result<Status, Error>

type function on Status

The status with code, or an Err outside 100 to 999.

import std::http.Status

assert Status.from_code(404) == Ok(Status.not_found)
assert Status.from_code(42) |> Result.is_err()
fn code(status: Status) -> Int

type function on Status

The status’s number.

fn text(status: Status) -> String

type function on Status

The reason phrase registered for the status, “Not Found” for 404, or "" for a code that has none.

import std::http.Status

assert Status.text(Status.not_found) == "Not Found"
assert Status.text(Status(599)) == ""
fn line(status: Status) -> String

type function on Status

The status line’s code and text: “404 Not Found”.

import std::http.Status

assert Status.line(Status.teapot) == "418 I'm a teapot"
fn is_informational(status: Status) -> Bool

type function on Status

1xx.

fn is_success(status: Status) -> Bool

type function on Status

2xx.

import std::http.Status

assert Status.is_success(Status.no_content)
assert not Status.is_success(Status.found)
fn is_redirect(status: Status) -> Bool

type function on Status

3xx.

fn is_client_error(status: Status) -> Bool

type function on Status

4xx.

fn is_server_error(status: Status) -> Bool

type function on Status

5xx.

impl Display for Status

fn to_string(status: Status) -> String

impl Display.to_string

The status line’s code and text, as Status.line.

impl Debug for Status

fn inspect(value: Status) -> String

impl Debug.inspect

impl Equatable for Status

fn equal(a: Status, b: Status) -> Bool

impl Equatable.equal

impl Hashable for Status

fn hash(value: Status) -> Int

impl Hashable.hash

type Headers List<(String, String)>

Header fields in order. A name may appear more than once, and names compare without case.

fn canonical_key(name: String) -> String

type function on Headers

name as HTTP writes header names, each word capitalized: content-type is Content-Type. A name that holds a space or other character a header name cannot is returned as it is.

import std::http.Headers

assert Headers.canonical_key("x-request-id") == "X-Request-Id"
fn get(headers: Headers, name: String) -> Maybe<String>

type function on Headers

The first value of name.

import std::http.Headers

h = Headers[("Accept", "text/html"), ("accept", "*/*")]
assert Headers.get(h, "ACCEPT") == Some("text/html")
assert Headers.values(h, "accept") == ["text/html", "*/*"]
fn values(headers: Headers, name: String) -> List<String>

type function on Headers

Every value of name, in order.

fn has(headers: Headers, name: String) -> Bool

type function on Headers

Whether name has a value.

fn set(headers: Headers, name: String, value: String) -> Headers

type function on Headers

The fields with name’s values replaced by value, in the place of its first value, or added at the end.

import std::http.Headers

h = Headers[("A", "1"), ("B", "2"), ("a", "3")]
assert Headers.set(h, "a", "9") == Headers[("A", "9"), ("B", "2")]
fn add(headers: Headers, name: String, value: String) -> Headers

type function on Headers

The fields with value added to name’s, at the end.

fn remove(headers: Headers, name: String) -> Headers

type function on Headers

The fields without name.

fn write_to(headers: Headers, w: io.Writer, except: List<String> = []) -> Result<Unit, io.Error>

type function on Headers

Writes the headers in wire format, Name: value lines each ending in CRLF, sorted by name, leaving out the names in except. A line break in a value is written as a space and the value is trimmed, so no value can add a line. It writes as Go’s Header.WriteSubset.

import std::http.Headers
import std::io.Writer

(_, written) = Writer.collect(fn w -> Headers.write_to(Headers[("b", "2"), ("A", "1")], w))
assert Bytes.to_string(written) == Ok("A: 1\r\nB: 2\r\n")

(_, folded) = Writer.collect(fn w -> Headers.write_to(Headers[("X", " a\r\nb ")], w))
assert Bytes.to_string(folded) == Ok("X: a  b\r\n")

impl Debug for Headers

fn inspect(value: Headers) -> String

impl Debug.inspect

impl Equatable for Headers

fn equal(a: Headers, b: Headers) -> Bool

impl Equatable.equal

enum Body
    Empty
    Text String
    Bytes Bytes
    Json Json
    Html Html
    Form Query
    Multipart List<FormPart>
    Stream Reader
    Produce (io.Writer) -> Result<Unit, io.Error>
end

A request’s or response’s body.

Variants

  • Text

    Sent with Content-Type: text/plain; charset=utf-8 unless the request sets one.

  • Json

    Encoded with Json.encode; sent with Content-Type: application/json unless the request sets one.

  • Html

    Rendered markup; sent with Content-Type: text/html; charset=utf-8 unless the request or response sets one.

  • Form

    URL-encoded; sent with Content-Type: application/x-www-form-urlencoded unless the request sets one.

  • Multipart

    A multipart/form-data form; sent with its Content-Type and boundary unless the request sets one.

  • Stream

    A stream, read once: a request’s body as a server receives it.

  • Produce

    A response body a function writes as the client reads it, for streaming and server-sent events: what it writes is sent each time the writer passes bytes on, at Writer.flush or when its buffer fills. A server’s response only; a request refuses it.

fn reader(body: Body) -> Reader

type function on Body

A Reader over the body.

fn read_all(body: Body) -> Result<Bytes, Error>

type function on Body

The whole body, a stream read to its end. It has no default limit: a request’s body is held whole in memory unless limit_body or the server’s max_body limits it. Request.form and multipart_form read with a default limit.

import std::http.Body

assert Body.read_all(Body.Text("hi")) == Ok(String.to_bytes("hi"))

impl Debug for Body

fn inspect(value: Body) -> String

impl Debug.inspect

enum FormPart
    Field { name: String, value: String }
    File { field: String, filename: String, content_type: String = "application/octet-stream", content: Bytes }
    Raw { headers: Headers, content: Bytes }
end

One part of a Body.Multipart form.

Variants

  • Field

    A field and its value: Go’s Writer.WriteField.

  • File

    A file: Go’s Writer.CreateFormFile, with a content type.

  • Raw

    A part with headers of its own: Go’s Writer.CreatePart.

fn encode(parts: List<FormPart>) -> {content_type: String, body: Bytes}

type function on FormPart

parts as a multipart body, and the Content-Type that names its boundary. The boundary is a digest of the parts, so the same parts always encode to the same bytes.

import std::http.FormPart

encoded = FormPart.encode([FormPart.Field{name: "a", value: "1"}])
assert String.starts_with(encoded.content_type, "multipart/form-data; boundary=")
fn file_disposition(field: String, filename: String) -> String

type function on FormPart

The Content-Disposition of a file part: Go’s multipart.FileContentDisposition.

import std::http.FormPart

assert FormPart.file_disposition("doc", "a.txt") == "form-data; name=\"doc\"; filename=\"a.txt\""

impl Debug for FormPart

fn inspect(value: FormPart) -> String

impl Debug.inspect

struct FormFile
    filename: String
    headers: Headers = Headers[]
    size: Int = 0
    content: Bytes
end

A file a multipart form holds: Go’s multipart.FileHeader.

fn open(file: FormFile) -> Reader

type function on FormFile

The file’s content as a stream.

impl Debug for FormFile

fn inspect(value: FormFile) -> String

impl Debug.inspect

struct MultipartForm
    values: Query = Query[]
    files: Map<String, List<FormFile>> = {}
end

A multipart form: Go’s multipart.Form.

impl Debug for MultipartForm

fn inspect(value: MultipartForm) -> String

impl Debug.inspect

struct Protocol
    major: Int = 1
    minor: Int = 1
end

An HTTP version.

fn is_at_least(protocol: Protocol, major: Int, minor: Int) -> Bool

type function on Protocol

Whether the version is major.minor or later.

import std::http.Protocol

assert Protocol.is_at_least(Protocol{major: 2, minor: 0}, 1, 1)
assert not Protocol.is_at_least(Protocol{major: 1, minor: 0}, 1, 1)
fn parse(text: String) -> Maybe<Protocol>

type function on Protocol

Reads an HTTP version: HTTP/, a digit, a . and a digit, as in HTTP/1.1.

import std::http.Protocol

assert Protocol.parse("HTTP/2.0") == Some(Protocol{major: 2, minor: 0})
assert Protocol.parse("HTTP/x") == None
assert Protocol.parse("HTTP/1.-1") == None

impl Display for Protocol

fn to_string(protocol: Protocol) -> String

impl Display.to_string

HTTP/1.1.

impl Debug for Protocol

fn inspect(value: Protocol) -> String

impl Debug.inspect

impl Equatable for Protocol

fn equal(a: Protocol, b: Protocol) -> Bool

impl Equatable.equal

struct Request
    method: Method = Method.Get
    url: Url
    headers: Headers = Headers[]
    body: Body = Body.Empty
    host: Maybe<String> = None
    content_length: Maybe<Int> = None
    transfer_encoding: List<String> = []
    close: Bool = False
    trailers: Headers = Headers[]
    body_limit: Maybe<Int> = None
    protocol: Protocol = Protocol{}
    remote_address: String = ""
    request_uri: String = ""
    pattern: Maybe<String> = None
    path_values: Map<String, String> = {}
    context: Context = Context.root()
    local_address: String = ""
    tls: Maybe<tls.ConnectionState> = None
    trace: Maybe<Tracer> = None
    incoming: Maybe<http_host.Incoming> = None
end

A request to send, or one a server received.

fn form(request: Request) -> Result<Query, Error>

type function on Request

The form’s fields: those of the body (post_form) and then the URL’s query. It reads the body, which a request can do once, so keep what it returns.

import std::http.{Method, Request}
import std::http::testing
import std::url.Query

r = testing.form_request(Method.Post, "/?b=2", [("a", "1")])
assert Request.form(r) == Ok(Query[("a", "1"), ("b", "2")])
fn post_form(request: Request) -> Result<Query, Error>

type function on Request

The fields of the body: a URL-encoded body of a POST, PUT or PATCH, or a multipart form’s fields. Empty for any other request. It reads the body, at most 10 MB of a URL-encoded one or the request’s body_limit, and returns Error.BodyTooLarge past that.

import std::http.{Body, Method, Request}
import std::http::testing

posted = fn size: Int ->
    {
        ..testing.request(Method.Post, "/"),
        headers: Headers[("Content-Type", "application/x-www-form-urlencoded")],
        body: Body.Stream(
            Reader.from_text("a=${String.repeat("x", NonNegativeInt.try_from(size - 2)!)}")
        ),
    }
end

assert Request.post_form(Request.limit_body(posted(8), 8)) |> Result.is_ok()

assert Request.post_form(Request.limit_body(posted(9), 8)) == Err(Error.BodyTooLarge{limit: 8})

twice = Request.limit_body(Request.limit_body(posted(9), 8), 100)
assert Request.post_form(twice) == Err(Error.BodyTooLarge{limit: 8})
fn form_value(request: Request, key: String) -> Maybe<String>

type function on Request

The first value of key in the form (form), or None when the form has none or does not parse.

fn post_form_value(request: Request, key: String) -> Maybe<String>

type function on Request

The first value of key in the body’s fields, as Go’s Request.PostFormValue.

fn multipart_form(request: Request) -> Result<MultipartForm, Error>

type function on Request

The multipart form the body holds, as Go’s Request.ParseMultipartForm. The whole form is read into memory, so a body past 32 MB, or past the request’s body_limit when it has one, is Error.BodyTooLarge; parts streams a larger one. It reads the body.

import std::http.{Body, FormPart, Method, Request}
import std::http::testing

file = fn text: String ->
    FormPart.File{field: "doc", filename: "a", content: String.to_bytes(text)}
end

upload = fn size: Int ->
    overhead = Bytes.length(FormPart.encode([file("")]).body)
    encoded = FormPart.encode([file(String.repeat("x", NonNegativeInt.try_from(size - overhead)!))])

    {
        ..testing.request(Method.Post, "/upload"),
        headers: Headers[("Content-Type", encoded.content_type)],
        body:    Body.Stream(Reader.from_bytes(encoded.body)),
    }
end

assert Request.multipart_form(upload(1000)) |> Result.is_ok()
assert Request.multipart_form(Request.limit_body(upload(1000), 1000)) |> Result.is_ok()

assert Request.multipart_form(Request.limit_body(upload(1000), 999))
    == Err(Error.BodyTooLarge{limit: 999})
fn form_file(request: Request, field: String) -> Result<FormFile, Error>

type function on Request

The first file in the multipart form’s field field, as Go’s Request.FormFile. It reads the body.

import std::http.{Body, FormPart, Method, Request}
import std::http::testing

parts = [
    FormPart.Field{name: "note", value: "hi"},
    FormPart.File{field: "doc", filename: "a.txt", content: String.to_bytes("abc")},
]

request = {
    ..testing.request(Method.Post, "/upload"),
    headers: Headers[("Content-Type", FormPart.encode(parts).content_type)],
    body:    Body.Multipart(parts),
}

file = Request.form_file(request, "doc")!
assert file.filename == "a.txt"
assert file.size == 3
assert Request.form_value(request, "note") == Some("hi")
assert Request.form_file(request, "nope") == Err(Error.MissingFile{field: "nope"})
fn text(request: Request) -> Result<String, Error>

type function on Request

The whole body as text. It reads at most 10 MB, or the request’s body_limit, as post_form does, and returns Error.BodyTooLarge past that; a body that is not UTF-8 is Error.MalformedBody, which a handler’s ? answers with a 400. It reads the body, which a request can do once.

import std::http.{Body, Method, Request}
import std::http::testing

posted = fn body: Body -> {..testing.request(Method.Post, "/notes"), body:}

assert Request.text(posted(Body.Stream(Reader.from_text("hello")))) == Ok("hello")

assert Request.text(Request.limit_body(posted(Body.Text("too long")), 4))
    == Err(Error.BodyTooLarge{limit: 4})

assert Request.text(posted(Body.Bytes(Bytes.from_list([255]))))
    == Err(Error.MalformedBody{reason: "the body is not UTF-8 text"})
fn json_as<T>(request: Request) -> Result<T, Error> where T: FromJson

type function on Request

The body read as JSON into a T: Request.text, then Json.decode_as. Text that is not JSON, or JSON that is not a T, is Error.MalformedBody, so a handler that returns Result<_, http.Error> answers it with a 400 through ?. It does not check the Content-Type. Give T with a binding’s annotation or as Request.json_as<T>(request).

import std::http.{Body, Method, Request, Response, Status}
import std::http::testing

posted = fn text: String -> {..testing.request(Method.Post, "/todos"), body: Body.Text(text)}

read: Result<Map<String, String>, Error> = Request.json_as(posted(`{"title": "milk"}`))
assert read == Ok({"title" => "milk"})

assert Request.json_as<List<Int>>(posted("[1,")) |> Result.is_err()

todo = Request.json_as<{title: String, order: Maybe<Int>}>(posted(`{"title": "milk"}`))
assert todo == Ok({title: "milk", order: None})

create = fn request: Request ->
    fields = Request.json_as<Map<String, String>>(request)?
    Ok(Response{status: Status.created, body: Body.Text("${Map.get(fields, "title")}")})
end

answer = fn text: String -> ToResponse.to_response(create(posted(text)))
assert answer(`{"title": "milk"}`).status == Status.created
assert answer(`{"title": 7}`).status == Status.bad_request

assert Response.text(answer(`{"title": 7}`))
    == Ok("malformed body: title: expected String, got int\n")
fn cookies(request: Request) -> List<Cookie>

type function on Request

The cookies the request’s Cookie headers send, as Go’s Request.Cookies; one that does not parse is left out.

import std::http.{Cookie, Method, Request}
import std::http::testing

r = Request.add_cookie(testing.request(Method.Get, "/"), Cookie{name: "a", value: "1"})
assert Request.cookie(r, "a") |> Maybe.map(fn c -> c.value) == Some("1")

spaced = Request.add_cookie(r, Cookie{name: "b", value: "x y"})
assert Headers.get(spaced.headers, "Cookie") == Some("a=1; b=\"x y\"")
fn cookies_named(request: Request, name: String) -> List<Cookie>

type function on Request

The cookies named name, as Go’s Request.CookiesNamed.

fn cookie(request: Request, name: String) -> Maybe<Cookie>

type function on Request

The first cookie named name, as Go’s Request.Cookie.

fn add_cookie(request: Request, cookie: Cookie) -> Request

type function on Request

The request with cookie added to its Cookie header. Only its name and value are sent; a character a value cannot carry is dropped, and a value with a space or a comma is quoted.

fn limit_body(request: Request, max: NonNegativeInt) -> Request

type function on Request

The request with a body that fails past max bytes, as Go’s MaxBytesReader: reading it then returns an io.Error, and the form readers Error.BodyTooLarge. max becomes the request’s body_limit, which replaces the form defaults, so an upload route can raise them; a second limit only lowers the first.

fn user_agent(request: Request) -> Maybe<String>

type function on Request

The User-Agent header.

fn referer(request: Request) -> Maybe<String>

type function on Request

The Referer header.

fn basic_auth(request: Request) -> Maybe<(String, String)>

type function on Request

The user and password of a Basic Authorization header, whose scheme may be written in any case.

import std::http.Request
import std::url.Url

r = Request.with_basic_auth(Request{url: Url"https://example.com"}, "ann", "pw")
assert Request.basic_auth(r) == Some(("ann", "pw"))

lower = {..r, headers: Headers[("Authorization", "basic YW5uOnB3")]}
assert Request.basic_auth(lower) == Some(("ann", "pw"))
fn with_basic_auth(request: Request, user: String, password: String) -> Request

type function on Request

The request with a Basic Authorization header for user and password.

fn extend_read_deadline(request: Request, by: Duration) -> Result<Unit, Error>

type function on Request

Lets the client take until by from now to send the rest of the body, past the server’s read_timeout. Go’s ResponseController.SetReadDeadline. An Err for a request no server received.

fn read(r: Reader) -> Result<Request, Error>

type function on Request

Reads one request from r as it arrives on the wire, its body read whole: Go’s ReadRequest. It reads no byte past the request, so the next one on r is left whole.

import std::http.{Request, Method}
import std::io.Reader

r = Reader.from_text("POST /a?b=1 HTTP/1.1\r\nHost: x\r\nContent-Length: 2\r\n\r\nhi")
request = Request.read(r)!
assert request.method == Method.Post
assert request.url.path == "/a"
assert Body.read_all(request.body) == Ok(String.to_bytes("hi"))
fn write_to(request: Request, w: Writer, proxy: Bool = False) -> Result<Unit, Error>

type function on Request

Writes the request to w as a client sends it: Go’s Request.Write, or with proxy its WriteProxy, which names the whole URL.

fn dump(request: Request, body: Bool = True) -> Result<String, Error>

type function on Request

The request as text, as a server received it: httputil’s DumpRequest. Without body, the body is left out. It reads the body.

import std::http.{Request, Method}
import std::url.Url

dumped = Request.dump(Request{method: Method.Get, url: Url.parse("http://x/a")!})!
assert String.starts_with(dumped, "GET /a HTTP/1.1")
fn dump_outgoing(request: Request, body: Bool = True) -> Result<String, Error>

type function on Request

The request as text, as a client sends it: httputil’s DumpRequestOut.

fn parts(request: Request) -> Result<Iter<Result<Part, Error>>, Error>

type function on Request

The parts of the request’s multipart body, read as the iterator runs, each in turn: Go’s Request.MultipartReader, for a body too large to read whole (multipart_form). An Err when the request is not multipart.

fn path_value(request: Request, name: String) -> Maybe<String>

type function on Request

The value a router matched for the wildcard name, or None when the matched pattern has no wildcard of that name.

fn with_path_value(request: Request, name: String, value: String) -> Request

type function on Request

The request with the wildcard name matched as value.

impl Debug for Request

fn inspect(value: Request) -> String

impl Debug.inspect

struct Response
    status: Status = Status.ok
    headers: Headers = Headers[]
    body: Body = Body.Empty
    trailers: Headers = Headers[]
    protocol: Protocol = Protocol{}
    url: Maybe<Url> = None
    content_length: Maybe<Int> = None
    transfer_encoding: List<String> = []
    close: Bool = False
    uncompressed: Bool = False
    tls: Maybe<tls.ConnectionState> = None
    write_timeout: Maybe<Duration> = None
    full_duplex: Bool = False
    upgrade: Maybe<(net.Connection) -> Unit> = None
end

A response a client received, or one a handler returns.

fn read(r: Reader, request: Request) -> Result<Response, Error>

type function on Response

Reads one response from r, to a request like request, its body read whole: Go’s ReadResponse.

fn write_to(response: Response, w: Writer) -> Result<Unit, Error>

type function on Response

Writes the response to w as a server sends it: Go’s Response.Write.

import std::http.{Body, Response}
import std::io.Writer

(_, wire) = Writer.collect(fn w -> Response.write_to(Response{body: Body.Text("hi")}, w))
assert String.starts_with(Bytes.to_string(wire)!, "HTTP/1.1 200 OK")
fn dump(response: Response, body: Bool = True) -> Result<String, Error>

type function on Response

The response as text: httputil’s DumpResponse. Without body, the body is left out.

fn upgrade(status: Status = Status.switching_protocols, headers: Headers, on_connection: (net.Connection) -> Unit) -> Response

type function on Response

A response that sends status and headers, then hands the connection to on_connection, which speaks another protocol over it, as a WebSocket server does after 101 Switching Protocols. The connection is closed when on_connection returns. Go’s Hijack.

fn cookies(response: Response) -> List<Cookie>

type function on Response

The cookies the response’s Set-Cookie headers set, as Go’s Response.Cookies; one that does not parse is left out.

fn set_cookie(response: Response, cookie: Cookie) -> Response

type function on Response

The response with a Set-Cookie header for cookie, as Go’s SetCookie; a cookie Go cannot write is left out.

import std::http.{Cookie, Response, SameSite}

r = Response.set_cookie(
    Response{},
    Cookie{name: "id", value: "7", http_only: True, same_site: SameSite.Lax},
)

assert Headers.get(r.headers, "Set-Cookie") == Some("id=7; HttpOnly; SameSite=Lax")
fn html(page: Html) -> Response

type function on Response

A page or a fragment of one: a 200 whose body is page, sent as text/html; charset=utf-8 with its length.

import std::html.Html
import std::http.Response
import std::io.Writer

page = Html.text("a < b")
(_, wire) = Writer.collect(fn w -> Response.write_to(Response.html(page), w))
sent = Bytes.to_string(wire)!
assert String.contains(sent, "Content-Type: text/html; charset=utf-8")
assert String.contains(sent, "Content-Length: 8")
assert String.ends_with(sent, "a &lt; b")
fn json(value: ToJson, status: Status = Status.ok) -> Response

type function on Response

value as JSON: a response with status, 200 unless given, whose body is ToJson.to_json(value), sent as application/json. A Json value is sent as it is, and an anonymous struct as an object of its fields.

import std::http.{Response, Status}

r = Response.json({"id" => 7, "done" => 0})
assert r.status == Status.ok
assert Headers.get(r.headers, "Content-Type") == Some("application/json")
assert Response.json_as<Map<String, Int>>(r) == Ok({"id" => 7, "done" => 0})

created = Response.json(Json.Obj{"id" => Json.Int(8)}, status: Status.created)
assert created.status == Status.created
assert Response.text(created) == Ok(`{"id":8}`)

missing = Response.json({error: "no todo 99"}, status: Status.not_found)
assert Response.text(missing) == Ok(`{"error":"no todo 99"}`)
fn error(status: Status, message: String) -> Response

type function on Response

A plain-text response with status and message, as Go’s Error writes it: text/plain; charset=utf-8, X-Content-Type-Options: nosniff, and the message and a newline.

import std::http.{Response, Status}

r = Response.error(Status.forbidden, "no")
assert Response.text(r) == Ok("no\n")
assert Headers.get(r.headers, "x-content-type-options") == Some("nosniff")
fn not_found() -> Response

type function on Response

A 404 whose plain-text body is 404 page not found.

fn redirect(request: Request, to: String, status: Status) -> Response

type function on Response

A redirect to to, which may be relative to the request’s path, with status and a short HTML body for a GET or HEAD.

import std::http.{Method, Response, Status}
import std::http::testing

r = Response.redirect(testing.request(Method.Get, "/a/b"), "c", Status.found)
assert Headers.get(r.headers, "Location") == Some("/a/c")
fn content(request: Request, name: String, modified: Maybe<Instant>, data: Bytes, headers: Headers = Headers[]) -> Response

type function on Response

data as the response to request. Its Content-Type comes from the extension of name, or from the data itself, unless headers sets one. A Range gets 206 and the parts asked for, and the If-* conditional headers are checked against modified and the ETag in headers, so an If-None-Match that names it is a 304. The response carries headers. It responds as Go’s ServeContent does.

import std::http.{Method, Response, Status}
import std::http::testing

request = testing.request(Method.Get, "/f")
ranged = {..request, headers: Headers.set(.., "Range", "bytes=1-2")}
r = Response.content(ranged, "f.txt", None, String.to_bytes("hello"))
assert r.status == Status.partial_content
assert Response.text(r) == Ok("el")

head = {..request, method: Method.Head}
assert Response.content(head, "f.txt", None, String.to_bytes("hello")).content_length == Some(5)

tagged = Headers[("ETag", "\"v1\"")]
again = {..request, headers: Headers.set(.., "If-None-Match", "\"v1\"")}

assert Response.content(again, "f.txt", None, String.to_bytes("hello"), headers: tagged).status
    == Status.not_modified
fn with_headers(value: ToResponse, headers: Headers) -> Response

type function on Response

value as a response, with each of headers set in place of any value the response has for that name. Middleware uses it on whatever its handler returned.

import std::html.Html
import std::http.Response

r = Response.with_headers(Html"<p>hi</p>", Headers[("Cache-Control", "no-store")])
assert Headers.get(r.headers, "Cache-Control") == Some("no-store")
assert Response.text(r) == Ok("<p>hi</p>")
fn with_default_headers(value: ToResponse, headers: Headers) -> Response

type function on Response

value as a response, with each of headers the response does not have already: a header the handler set is kept.

import std::http.Response

r = Response.with_default_headers(
    Response{headers: Headers[("X-Frame-Options", "SAMEORIGIN")]},
    Headers[("X-Frame-Options", "DENY"), ("Referrer-Policy", "no-referrer")],
)

assert Headers.get(r.headers, "X-Frame-Options") == Some("SAMEORIGIN")
assert Headers.get(r.headers, "Referrer-Policy") == Some("no-referrer")
fn text(response: Response) -> Result<String, Error>

type function on Response

The whole body as text.

fn bytes(response: Response) -> Result<Bytes, Error>

type function on Response

The whole body.

fn json_as<T>(response: Response) -> Result<T, Error> where T: FromJson

type function on Response

The whole body read as JSON into a T: Response.text, then Json.decode_as. Text that is not JSON, or JSON that is not a T, is Error.Protocol. It does not check the Content-Type. Give T with a binding’s annotation or as Response.json_as<T>(response); Response.json_as<Json> reads any JSON.

import std::http.{Body, Response}

r = Response{body: Body.Text(`{"id": 7}`)}
assert Response.json_as<Map<String, Int>>(r) == Ok({"id" => 7})
assert Response.json_as<Json>(r) == Ok(Json.Obj{"id" => Json.Int(7)})
assert Response.json_as<List<Int>>(r) |> Result.is_err()
fn location(response: Response) -> Result<Maybe<Url>, Error>

type function on Response

The Location header resolved against the response’s URL.

impl ToResponse for Response

fn to_response(value: Response) -> Response

impl ToResponse.to_response

impl Debug for Response

fn inspect(value: Response) -> String

impl Debug.inspect

interface ToResponse
    fn to_response(value: self) -> Response
end

A value a handler may return: every place std::http takes a handler takes a Handler, a (Request) -> ToResponse, and calls to_response once on what it returns. A handler with several steps that can fail returns Result<Response, AppError> and uses ?, and the program’s error type implements ToResponse to render itself, as axum’s IntoResponse does.

Response is sent as it is, Html as Response.html makes it (a 200 page), and a Result as its Ok or its Err. String has no implementation: a handler that returns text says which kind with Body.Text, Response.error or a content type of its own.

import std::html.Html
import std::http.{self, Body, Method, Response, Route, Router, Status}
import std::http::testing

router = Router.new([
    Route.to("GET /plain", fn _ -> Response{body: Body.Text("plain")}),
    Route.to("GET /page", fn _ -> Html"<p>page</p>"),
    Route.to_with("GET /items/{id}", fn _, p ->
        case String.to_int(p.id)
            Some(n) -> Ok(Response{body: Body.Text("item ${n}")})
            None    -> Err(Response.error(Status.bad_request, "not a number"))
        end
    end),
])!

answer = fn target: String -> Router.serve(router, testing.request(Method.Get, target))
assert Response.text(answer("/plain")) == Ok("plain")
assert Response.text(answer("/page")) == Ok("<p>page</p>")
assert Response.text(answer("/items/7")) == Ok("item 7")
assert answer("/items/x").status == Status.bad_request
fn to_response(value: self) -> Response

interface ToResponse

typealias Handler (Request) -> ToResponse

A request handler: a function from a Request to any value that converts to a response (ToResponse). Router.new, serve and the middleware take one. A named function or a lambda is one as it stands.

impl ToResponse for Error

fn to_response(error: Error) -> Response

impl ToResponse.to_response

enum Error
    InvalidUrl { url: String, reason: String }
    InvalidRequest { reason: String }
    Dns { host: String, reason: String }
    Connect { address: String, reason: String }
    Tls { reason: String }
    Timeout { during: String }
    Canceled
    TooManyRedirects { count: Int }
    Form { reason: String }
    MissingFile { field: String }
    CrossOrigin { reason: String }
    RedirectRefused { url: String, reason: String }
    Protocol { reason: String }
    BodyTooLarge { limit: Int }
    MalformedBody { reason: String }
    BodyNotAllowed
    ContentLength
    HandlerTimeout
    Body { error: io.Error }
    Listen { address: String, reason: String }
    Pattern { pattern: String, reason: String }
    Unsupported { reason: String }
end

Why a request got no response.

Variants

  • Timeout

    The client’s timeout, a deadline in force, or a transport timeout.

  • Form

    A form that does not parse, or a request that holds none of the kind asked for.

  • MissingFile

    Request.form_file found no file in the field.

  • CrossOrigin

    CrossOrigin.check refused a cross-origin request.

  • RedirectRefused

    A Redirects.Decide function refused the redirect to url.

  • MalformedBody

    A request body Request.text or json_as could not read as asked: not UTF-8, not JSON, or JSON of another shape.

  • Listen

    A server could not listen on address.

  • Pattern

    A router pattern that breaks Route’s rules or that Go’s ServeMux refuses, or one that conflicts with an earlier pattern.

  • Unsupported

    The target has no network.

fn is_timeout(error: Error) -> Bool

type function on Error

Whether the error is a timeout, as Go’s Timeout() reports.

impl Display for Error

fn to_string(error: Error) -> String

impl Display.to_string

impl Debug for Error

fn inspect(value: Error) -> String

impl Debug.inspect

impl Equatable for Error

fn equal(a: Error, b: Error) -> Bool

impl Equatable.equal

enum Redirects
    Follow { max: Int = 10 }
    Never
    Decide (Request, List<Request>) -> Redirect
end

Which redirects a client follows.

Variants

  • Follow

    Follow up to max redirects, as Go does (10).

  • Never

    Return the redirect response itself.

  • Decide

    Ask a function before each redirect, as Go’s CheckRedirect does. It gets the request the redirect would send and the requests already sent, oldest first, and returns whether to send it. There is no limit but the function’s.

impl Debug for Redirects

fn inspect(value: Redirects) -> String

impl Debug.inspect

enum Redirect
    Follow
    Stop
    Refuse String
end

What a Redirects.Decide function returns for one redirect.

Variants

  • Follow

    Send the request.

  • Stop

    Return the redirect response itself, as Go’s ErrUseLastResponse.

  • Refuse

    Fail the request with Error.RedirectRefused and reason.

impl Debug for Redirect

fn inspect(value: Redirect) -> String

impl Debug.inspect

enum Proxy
    FromEnvironment
    Direct
    Fixed Url
end

Where a client’s requests go through.

Variants

  • FromEnvironment

    HTTP_PROXY, HTTPS_PROXY and NO_PROXY, as Go reads them.

  • Direct

    No proxy.

  • Fixed

    Every request through url.

impl Debug for Proxy

fn inspect(value: Proxy) -> String

impl Debug.inspect

struct Transport
    proxy: Proxy = Proxy.FromEnvironment
    tls_handshake_timeout: Duration = Duration.seconds(10)
    keep_alives: Bool = True
    compression: Bool = True
    max_idle: Int = 100
    max_idle_per_host: Int = 2
    max_per_host: Maybe<Int> = None
    idle_timeout: Maybe<Duration> = Some(Duration.seconds(90))
    response_header_timeout: Maybe<Duration> = None
    expect_continue_timeout: Duration = Duration.seconds(1)
    max_response_header_bytes: Maybe<Int> = None
    write_buffer_size: Maybe<Int> = None
    read_buffer_size: Maybe<Int> = None
    force_http2: Bool = True
    protocols: Maybe<Protocols> = None
    http2: Http2Options = Http2Options{}
    proxy_connect_headers: Headers = Headers[]
    on_proxy_connect: Maybe<(Url, Response) -> Result<Unit, Error>> = None
end

How a client’s connections are made and kept: Go’s Transport options. A timeout past about 292 years, the longest wait the clock counts, never fires.

once default: Transport

struct Transport
    proxy: Proxy
    tls_handshake_timeout: Duration
    keep_alives: Bool
    compression: Bool
    max_idle: Int
    max_idle_per_host: Int
    max_per_host: Maybe<Int>
    idle_timeout: Maybe<Duration>
    response_header_timeout: Maybe<Duration>
    expect_continue_timeout: Duration
    max_response_header_bytes: Maybe<Int>
    write_buffer_size: Maybe<Int>
    read_buffer_size: Maybe<Int>
    force_http2: Bool
    protocols: Maybe<Protocols>
    http2: Http2Options
    proxy_connect_headers: Headers
    on_proxy_connect: Maybe<(Url, Response) -> Result<Unit, Error>>
end

The options Go’s DefaultTransport has.

impl Debug for Transport

fn inspect(value: Transport) -> String

impl Debug.inspect

struct Protocols
    http1: Bool = True
    http2: Bool = True
    unencrypted_http2: Bool = False
end

The HTTP protocols a server accepts or a transport speaks: Go’s Protocols.

impl Display for Protocols

fn to_string(protocols: Protocols) -> String

impl Display.to_string

import std::http.Protocols

assert "${Protocols{}}" == "{HTTP1,HTTP2}"

impl Debug for Protocols

fn inspect(value: Protocols) -> String

impl Debug.inspect

impl Equatable for Protocols

fn equal(a: Protocols, b: Protocols) -> Bool

impl Equatable.equal

struct Http2Options
    max_concurrent_streams: Maybe<Int> = None
    strict_max_concurrent_requests: Bool = False
    max_decoder_header_table_size: Maybe<Int> = None
    max_encoder_header_table_size: Maybe<Int> = None
    max_read_frame_size: Maybe<Int> = None
    max_receive_buffer_per_connection: Maybe<Int> = None
    max_receive_buffer_per_stream: Maybe<Int> = None
    send_ping_timeout: Maybe<Duration> = None
    ping_timeout: Maybe<Duration> = None
    write_byte_timeout: Maybe<Duration> = None
    permit_prohibited_cipher_suites: Bool = False
    on_error_count: Maybe<(String) -> Unit> = None
end

HTTP/2’s limits and timeouts: Go’s HTTP2Config. None and False are Go’s defaults.

impl Debug for Http2Options

fn inspect(value: Http2Options) -> String

impl Debug.inspect

struct StreamedResponse
    status: Status
    headers: Headers
    body: Reader
    protocol: Protocol
    url: Maybe<Url>
    content_length: Maybe<Int>
    tls: Maybe<tls.ConnectionState>
end

A response whose body is still arriving: what http.stream and Client.stream return. It holds its connection until its body is closed, so defer StreamedResponse.close(response) follows it (spec §9 Releasing resources). http.fetch’s Response holds its body whole.

fn close(response: StreamedResponse) -> Unit

type function on StreamedResponse

Closes the body, so its connection is released.

impl Release for StreamedResponse

fn release(response: StreamedResponse) -> Unit

impl Release.release

impl Debug for StreamedResponse

fn inspect(value: StreamedResponse) -> String

impl Debug.inspect

struct ClientOptions
    timeout: Maybe<Duration> = None
    redirects: Redirects = Redirects.Follow{}
    transport: Transport = Transport.default
    round_trip: Maybe<(Request) -> Result<Response, Error>> = None
    max_body: Maybe<Int> = Some(67_108_864)
    cookies: Maybe<CookieJar> = None
end

A client’s options. A timeout past about 292 years, the longest wait the clock counts, never fires.

impl Debug for ClientOptions

fn inspect(value: ClientOptions) -> String

impl Debug.inspect

struct Client
    handle: http_host.Client
    options: ClientOptions
end

A client: its options and its connection pool. Make one with Client.new and keep it; the pool is Go’s, which only std::http can name.

fn new(options: ClientOptions = ClientOptions{}) -> Client

type function on Client

A client with options.

fn with_tls(client: Client, config: tls.ClientConfig) -> Result<Client, tls.Error>

type function on Client

The client checking servers and offering what config says over TLS, in place of Go’s defaults, with the same options and cookies, or the tls.Error for a config Go cannot build: roots that hold no certificate, a roots file that cannot be read, or a certificate or key that does not parse.

import std::tls.{ClientConfig, Roots}

assert Client.new() |> Client.with_tls(ClientConfig{roots: Roots.Pem("none")}) |> Result.is_err()
assert Client.new() |> Client.with_tls(ClientConfig{}) |> Result.is_ok()
fn fetch(client: Client, request: Request) -> Result<Response, Error>

type function on Client

Sends request and reads the whole body into Body.Bytes.

fn stream(client: Client, request: Request) -> Result<StreamedResponse, Error>

type function on Client

Sends request and returns the response with its body still arriving, read as it arrives, of any size. Defer StreamedResponse.close on the next line, so the body is closed however the function ends. A faked or round-tripped response’s body is read from memory.

fn get(client: Client, url: Url) -> Result<Response, Error>

type function on Client

A GET of url.

fn head(client: Client, url: Url) -> Result<Response, Error>

type function on Client

A HEAD of url.

fn post(client: Client, url: Url, body: Body) -> Result<Response, Error>

type function on Client

A POST of body to url.

fn post_form(client: Client, url: Url, form: Query) -> Result<Response, Error>

type function on Client

A POST of form, URL-encoded, to url.

fn close_idle(client: Client) -> Unit

type function on Client

Closes the client’s idle connections.

impl Debug for Client

fn inspect(value: Client) -> String

impl Debug.inspect

fn default_client() -> Client

The client http.fetch and the other module functions use: the default options over one connection pool the whole program shares, as Go’s DefaultClient. std::http::testing.run responds in its place.

fn fetch(request: Request) -> Result<Response, Error>

Sends request with the default client and reads the whole response.

fn stream(request: Request) -> Result<StreamedResponse, Error>

Sends request with the default client and returns the response with its body still arriving, as Client.stream does. Defer StreamedResponse.close on the next line.

response = http.stream(Request{url:})?

defer StreamedResponse.close(response)
import std::http.{Body, Request, Response, StreamedResponse}
import std::http::testing
import std::url.Url

fn first_line(url: Url) -> Result<Maybe<String>, Error>
    response = stream(Request{url:})?
    defer StreamedResponse.close(response)
    Reader.read_line(response.body) |> Result.map_err(fn e -> Error.Body{error: e})
end

ran = testing.run(fn _ -> Ok(Response{body: Body.Text("one\ntwo\n")}), fn ->
    first_line(Url"https://example.com/log")
end)

assert ran.value == Ok(Some("one"))
fn get(url: Url) -> Result<Response, Error>

A GET of url with the default client.

fn head(url: Url) -> Result<Response, Error>

A HEAD of url with the default client.

fn post(url: Url, body: Body) -> Result<Response, Error>

A POST of body to url with the default client.

fn post_form(url: Url, form: Query) -> Result<Response, Error>

A POST of form to url with the default client.

struct Server
    address: String = ":http"
    read_timeout: Maybe<Duration> = None
    read_header_timeout: Maybe<Duration> = None
    write_timeout: Maybe<Duration> = None
    idle_timeout: Maybe<Duration> = None
    max_header_bytes: Int = 1_048_576
    max_body: Maybe<NonNegativeInt> = None
    keep_alives: Bool = True
    request_timeout: Maybe<Duration> = None
    shutdown_timeout: Duration = Duration.seconds(5)
    tls: Maybe<tls.ServerConfig> = None
    max_header_value_count: Maybe<Int> = None
    answer_options_star: Bool = True
    client_priority: Bool = True
    protocols: Maybe<Protocols> = None
    http2: Http2Options = Http2Options{}
    on_connection_state: Maybe<(String, ConnState) -> Unit> = None
    on_error: Maybe<(String) -> Unit> = None
    on_shutdown: Maybe<() -> Unit> = None
end

How a server listens and responds. A timeout of None is none, and one past about 292 years, the longest wait the clock counts, never fires.

impl Debug for Server

fn inspect(value: Server) -> String

impl Debug.inspect

struct Listener
    handle: http_host.Listener
    server: Server
end

A server listening for requests: listen binds it, and serve responds to what arrives.

fn address(listener: Listener) -> String

type function on Listener

The address the server is bound to, with the port it picked when its address asked for port 0.

fn shutdown(listener: Listener) -> Unit

type function on Listener

Stops the server as Go’s Server.Shutdown does: it stops accepting, waits up to the server’s shutdown_timeout for the requests it is serving, then closes every connection. A second call does nothing.

fn close_connections(listener: Listener) -> Unit

type function on Listener

Closes every connection the server holds, idle or busy; the server goes on accepting.

impl Debug for Listener

fn inspect(value: Listener) -> String

impl Debug.inspect

fn listen(server: Server = Server{}) -> Result<Listener, Error>

Binds the server’s address. The server accepts connections from here on; serve responds to the requests they send.

fn serve(listener: Listener, handler: Handler, supervisor: Supervisor) -> Unit

Serves each request listener receives with handler, each as a task of supervisor, so its max_running bounds the requests served at once. Returns when the calling task is stopped, as at shutdown, after shutting the listener down.

A handler runs under the request’s context: the context in force here, with the server’s request_timeout as a deadline. The app’s Context field reads it while the handler runs, and request.context holds it. The handler’s task is stopped when the client goes away. A handler that traps sends a 500. Use a supervisor that does not restart its tasks (Restart.Temporary, the default); a restarted handler sends nothing.

When the program shuts down, at a signal or when main returns, the server stops accepting at once, as Go’s Server.Shutdown does. The requests it took run to their end, for up to the server’s shutdown_timeout and the supervisor’s, and then serve returns.

type Route<P = Unit> String

opaque — construction surface is private to its defining module

A pattern a Router routes by, as Go’s ServeMux reads it: [METHOD ][HOST]/PATH, where a path segment {name} matches one segment, a last {name...} the rest of the path, and {$} only the end. A pattern with no method matches every method.

P is the route’s path parameters: an anonymous struct with a field per wildcard, Route<{id: Uuid}> for GET /posts/{id}, or Unit for a route with none, which is the default: a Route is a Route<Unit>. A field’s type implements Parse and Display, and a {rest...} field is a String. A literal with no expected type has a String field per wildcard, so Route"GET /users/{id}" is a Route<{id: String}>; a typed one names its fields’ types: post: Route<{id: Uuid}> = "GET /posts/{id}". Route.to_with hands a handler the parsed parameters and Route.path_with fills them into a link. The parameters are a type only: a Route holds its text.

Two rules are stricter than Go’s. The method is one of Method’s named variants, written in capitals as on the wire (GET, HEAD, POST, PUT, PATCH, DELETE, CONNECT, OPTIONS, TRACE), so a misspelled GETX is an error rather than a route no request reaches; Route.with_method takes any other. A { or } appears only in a wildcard that is a whole segment, so /token} is an error rather than a literal segment; a path that needs a brace percent-encodes it (%7B, %7D).

A Route literal is checked when the program is checked, so a pattern that breaks these rules, that Go refuses, or whose wildcards are not P’s fields is a compile error at the literal. A pattern built at run time goes through Route.parse.

assert "${Route"GET /users/{id}"}" == "GET /users/{id}"
assert Route.parse<Unit>("GET /a/{x}/{x}") |> Result.is_err()
assert Route.parse<{rest: String}>("/files/{rest...}/more") |> Result.is_err()
assert Route.parse<Unit>("GETX /complete-profile/token}") |> Result.is_err()
assert Route.parse<Unit>("/a/%7Bliteral%7D") |> Result.is_ok()
fn parse<P>(text: String) -> Result<Route<P>, Error> where P: ParseFields

type function on Route

The route text names, or Error.Pattern with the reason when it breaks Route’s rules, Go’s ServeMux refuses it, or its wildcards are not P’s fields. The method, when there is one, is a standard one in capitals; a near miss names the method it is close to.

assert Route.parse("POST /orders") == Ok(Route"POST /orders")
assert Err(Error.Pattern{reason:}) = Route.parse<Unit>("GET users")
assert String.contains(reason, "/")

assert Route.parse<Unit>("GETX /complete-profile") == Err(Error.Pattern{
        pattern: "GETX /complete-profile",
        reason:  "unknown method `GETX`; did you mean `GET`?",
    })

assert Err(Error.Pattern{reason: lower}) = Route.parse<Unit>("get /orders")
assert lower == "unknown method `get`; did you mean `GET`?"

assert Err(Error.Pattern{reason: webdav}) = Route.parse<Unit>("PROPFIND /files")
assert webdav == "unknown method `PROPFIND`; a route's method is GET, HEAD, POST, PUT, PATCH, DELETE, CONNECT, OPTIONS or TRACE, and `Route.with_method` takes any other"

assert Err(Error.Pattern{reason: closing}) = Route.parse<Unit>("GET /complete-profile/token}")
assert closing == "a `}` outside a wildcard; a wildcard is a whole segment, `{name}`"

assert Err(Error.Pattern{reason: opening}) = Route.parse<Unit>("/files/v{n}")
assert opening == "a `{` outside a wildcard; a wildcard is a whole segment, `{name}`"

assert Route.parse<{id: Int}>("GET /items/{id}") |> Result.is_ok()
assert Err(Error.Pattern{reason: fields}) = Route.parse<{id: Int}>("GET /items/{key}")
assert fields == "the pattern's wildcards are {key}, and the parameters' fields are id"
fn with_method<P>(method: Method, path: String) -> Result<Route<P>, Error> where P: ParseFields

type function on Route

The route of method on path ([HOST]/PATH), for a method a Route literal does not take: one Method.Other holds, such as WebDAV’s PROPFIND. A standard method is written in the literal, Route"GET /files". The path keeps the literal’s rule for braces, the method is a token Go accepts, with no space, and the wildcards are P’s fields, as Route.parse holds them.

import std::http.{Body, Method, Request, Response, Route, Router}
import std::http::testing

propfind = Route.with_method<{name: String}>(Method.Other("PROPFIND"), "/files/{name}")!
assert "${propfind}" == "PROPFIND /files/{name}"

router = Router.new([Route.to_with(propfind, fn _, p -> Response{body: Body.Text(p.name)})])!

answer = Router.serve(router, testing.request(Method.Other("PROPFIND"), "/files/a.txt"))
assert Response.text(answer) == Ok("a.txt")

assert Route.with_method<Unit>(Method.Get, "/a") == Ok(Route"GET /a")
assert Route.with_method<Unit>(Method.Other(""), "/a") |> Result.is_err()
assert Route.with_method<Unit>(Method.Other("PROP FIND"), "/a") |> Result.is_err()
assert Route.with_method<Unit>(Method.Other("PROPFIND"), "/a}") |> Result.is_err()
fn path(route: Route) -> Url

type function on Route

The path a route with no parameters matches, for a link: the pattern without its method or host, and a {$} dropped. A route with parameters fills them with Route.path_with.

assert "${Route.path(Route"GET /about")}" == "/about"
assert "${Route.path(Route"GET example.com/docs/{$}")}" == "/docs/"
fn path_with<P>(route: Route<P>, params: P) -> Url where P: ParseFields

type function on Route

The path the route matches with params in its wildcards, for a link: each field’s Display text escaped as one path segment, a {rest...} field’s text escaped segment by segment, and the pattern’s method and host left out.

users = Route"GET /users/{name}/posts/{rest...}"
link = Route.path_with(users, {name: "ann b", rest: "2024/a?b"})
assert "${link}" == "/users/ann%20b/posts/2024/a%3Fb"
fn to(route: Route, handler: Handler) -> Entry

type function on Route

The router entry that sends a request the route matches to handler, for a route with no parameters. A route with parameters hands them to its handler with Route.to_with.

fn to_with<P>(route: Route<P>, handler: (Request, P) -> ToResponse) -> Entry where P: ParseFields

type function on Route

The router entry that sends a request the route matches to handler, with its path parameters read into P, each wildcard’s text by its field’s Parse. A request whose wildcard text does not parse gets 404, as if no route matched: GET /posts/{id} with an id: Int does not match /posts/latest.

import std::http.{Body, Method, Response, Route, Router, Status}
import std::http::testing

item: Route<{id: Int}> = "GET /items/{id}"

router = Router.new(
    [Route.to_with(item, fn _, p -> Response{body: Body.Text("item ${p.id + 1}")})]
)!

answer = fn target: String -> Router.serve(router, testing.request(Method.Get, target))
assert Response.text(answer("/items/7")) == Ok("item 8")
assert answer("/items/x").status == Status.not_found

impl CheckedLiteral<String, Route<P>> for Route<P>

fn check(statics: List<String>) -> Result<Unit, LiteralError>

impl CheckedLiteral.check

impl CheckedLiteral<String, Route<P>> for Route<P>

fn check_type(statics: List<String>, arguments: List<String>) -> Result<Unit, LiteralError>

impl CheckedLiteral.check_type

impl CheckedLiteral<String, Route<P>> for Route<P>

fn build(fragments: List<Fragment<String>>) -> Route<P>

impl CheckedLiteral.build

impl Display for Route<P>

fn to_string(route: Route<P>) -> String

impl Display.to_string

impl Debug for Route<P>

fn inspect<P>(value: Route<P>) -> String where P: Debug

impl Debug.inspect

impl Equatable for Route<P>

fn equal<P>(a: Route<P>, b: Route<P>) -> Bool where P: Equatable

impl Equatable.equal

impl Hashable for Route<P>

fn hash<P>(value: Route<P>) -> Int where P: Hashable

impl Hashable.hash

struct Entry

opaque — construction surface is private to its defining module

A route and the handler it sends requests to, for Router.new: Route.to and Route.to_with make one. It leaves out the route’s parameters type, so routes with different parameters fit one list.

impl Display for Entry

fn to_string(entry: Entry) -> String

impl Display.to_string

impl Debug for Entry

fn inspect(value: Entry) -> String

impl Debug.inspect

struct Router
    mux: http_host.Mux
    handlers: List<(Request) -> Maybe<Response>>
end

Routes requests to handlers by pattern, with the rules of Go’s ServeMux: [METHOD ][HOST]/PATH, where a path segment {name} matches one segment, a last {name...} the rest of the path, and {$} only the end. The most specific pattern wins; GET also matches HEAD. A request whose path is not clean, or that lacks a trailing slash a pattern has, is redirected; one whose path matches only under another method gets 405 with Allow; anything else gets 404.

import std::http.{Body, Method, Request, Response, Route, Router, Status}
import std::http::testing

router = Router.new([
    Route.to_with("GET /users/{id}", fn _, p -> Response{body: Body.Text("user ${p.id}")}),
    Route.to("/files/", fn r -> Response{body: Body.Text(r.url.path)}),
    Route.to_with("/raw/{path...}", fn r, _ -> Response{
        body: Body.Text(Request.path_value(r, "path")!),
    }),
])!

user = Router.serve(router, testing.request(Method.Get, "/users/7"))
assert Response.text(user) == Ok("user 7")

assert Response.text(Router.serve(router, testing.request(Method.Get, "/raw/a/b.txt")))
    == Ok("a/b.txt")

assert Router.serve(router, testing.request(Method.Post, "/users/7")).status
    == Status.method_not_allowed

assert Router.serve(router, testing.request(Method.Get, "/nope")).status == Status.not_found
fn new(routes: List<Entry>) -> Result<Router, Error>

type function on Router

A router over routes, each a route and its handler from Route.to or Route.to_with, in order. A pattern that conflicts with an earlier one, matching the same requests with neither more specific, is Error.Pattern, where Go’s Handle panics. Each pattern on its own was checked when it became a Route.

import std::http.{Error, Response, Route, Router}

conflict = Router.new(
    [Route.to_with("/a/{x}", fn _, _ -> Response{}), Route.to_with("/a/{y}", fn _, _ -> Response{})]
)

assert Result.is_err(conflict)
fn find(router: Router, request: Request) -> Maybe<String>

type function on Router

The pattern that matches request, or None when none does, as Go’s ServeMux.Handler finds it.

fn serve(router: Router, request: Request) -> Response

type function on Router

Serves request with the handler of the pattern that matches it, with request.pattern and its path values set, or with what the router sends itself: a redirect, a 405 or a 404. A route whose parameters do not parse from the request’s path is a 404 too.

fn handler(router: Router) -> (Request) -> Response

type function on Router

The router as a handler, for http.serve.

impl Debug for Router

fn inspect(value: Router) -> String

impl Debug.inspect

fn not_found(Request) -> Response

A handler that responds to every request with Response.not_found.

fn redirect_to(to: String, status: Status) -> (Request) -> Response

A handler that redirects every request to to with status (Response.redirect).

fn strip_prefix(handler: Handler, prefix: String) -> (Request) -> Response

Middleware that removes prefix from the request’s path, and from its escaped form, before handler sees it, and returns 404 for a path without it.

import std::http.{Body, Method, Request, Response}
import std::http::testing
import std::url.Url

show = http.strip_prefix(fn r -> Response{body: Body.Text(Url.escaped_path(r.url))}, "/static")
assert Response.text(show(testing.request(Method.Get, "/static/a.css"))) == Ok("/a.css")
assert show(testing.request(Method.Get, "/a.css")).status == Status.not_found

assert Response.text(show(testing.request(Method.Get, "/static/a%2Fb.css"))) == Ok("/a%2Fb.css")
fn allow_query_semicolons(handler: Handler) -> (Request) -> Response

Middleware that reads a ; in the query as a &, for clients that still separate fields with ;. Without it, a ; in the query is an error to Query.parse.

import std::http.{self, Body, Method, Request, Response}
import std::http::testing
import std::url.{Query, Url}

seen = http.allow_query_semicolons(fn r -> Response{
    body: Body.Text(Query.encode(Url.query_values(r.url))),
})

response = seen(testing.request(Method.Get, "/?a=1;b=2"))
assert Response.text(response) == Ok("a=1&b=2")
fn timeout(handler: Handler, after: Duration, message: String) -> (Request) -> Response

Middleware that returns 503 Service Unavailable with message when handler has not returned within after, and stops the handler’s task.

import std::duration.Duration
import std::http.{self, Body, Method, Request, Response, Status}
import std::http::testing
import std::timer

sleepy = fn _: Request ->
    timer.sleep(Duration.seconds(5))
    Response{body: Body.Text("late")}
end

slow = sleepy |> http.timeout(Duration.milliseconds(20), "too slow")
assert slow(testing.request(Method.Get, "/")).status == Status.service_unavailable

fast = http.timeout(
    fn _: Request -> Response{body: Body.Text("ok")},
    Duration.milliseconds(20),
    "too slow",
)

assert Response.text(fast(testing.request(Method.Get, "/"))) == Ok("ok")
type Origin String

opaque — construction surface is private to its defining module

A web origin, scheme://host[:port], as a browser sends it in an Origin header: no path, query, fragment or user. Origin"https://app.example.com" is checked when the program is checked; Origin.parse checks one read at run time. The scheme and host are kept in lowercase, as a browser writes them, so an origin compares equal to the header’s text.

import std::http.Origin

assert "${Origin"HTTPS://App.Example.com:8443"}" == "https://app.example.com:8443"
assert Origin.parse("https://app.example.com/") |> Result.is_err()
assert Origin.parse("app.example.com") |> Result.is_err()
fn parse(text: String) -> Result<Origin, Error>

type function on Origin

The origin text names, or Error.InvalidUrl when it is not scheme://host[:port].

import std::http.{Error, Origin}

assert Origin.parse("http://localhost:5173") == Ok(Origin"http://localhost:5173")
assert Err(Error.InvalidUrl{url: _, reason:}) = Origin.parse("https://a.example?x=1")
assert String.contains(reason, "scheme://host")

impl Literal for Origin

fn from_fragments(fragments: List<Fragment<String>>) -> Result<Origin, Error>

impl Literal.from_fragments

impl Display for Origin

fn to_string(origin: Origin) -> String

impl Display.to_string

impl Debug for Origin

fn inspect(value: Origin) -> String

impl Debug.inspect

impl Equatable for Origin

fn equal(a: Origin, b: Origin) -> Bool

impl Equatable.equal

impl Hashable for Origin

fn hash(value: Origin) -> Int

impl Hashable.hash

struct CrossOrigin
    trusted_origins: List<Origin> = []
    bypass_patterns: List<Route> = []
    deny: Maybe<Handler> = None
end

Which cross-origin requests to let through, for cross_origin_protection, which guards against cross-site request forgery. A GET, HEAD or OPTIONS always passes.

fn check(options: CrossOrigin, request: Request) -> Result<Unit, Error>

type function on CrossOrigin

Whether request passes: a safe method passes; then a Sec-Fetch-Site of same-origin or none, or else an Origin whose host is the request’s Host, or none at all (not a browser); and any request from a trusted origin. An empty header counts as missing. The bypass patterns are cross_origin_protection’s to apply. The check is Go’s CrossOriginProtection.Check, with its reasons.

import std::http.{CrossOrigin, Method, Origin, Request}
import std::http::testing

post = testing.request(Method.Post, "/pay")

from = fn site: String -> {
    ..post,
    headers: Headers[("Sec-Fetch-Site", site), ("Origin", "https://evil.example")],
}

assert CrossOrigin.check(CrossOrigin{}, from("same-origin")) == Ok(Unit)
assert CrossOrigin.check(CrossOrigin{}, from("cross-site")) |> Result.is_err()

trusting = CrossOrigin{trusted_origins: [Origin"https://evil.example"]}
assert CrossOrigin.check(trusting, from("cross-site")) == Ok(Unit)

no_origin = {..post, headers: Headers[("Sec-Fetch-Site", ""), ("Origin", "")]}
assert CrossOrigin.check(CrossOrigin{}, no_origin) == Ok(Unit)

impl Debug for CrossOrigin

fn inspect(value: CrossOrigin) -> String

impl Debug.inspect

fn cross_origin_protection(handler: Handler, options: CrossOrigin) -> (Request) -> Response

Middleware that sends a request CrossOrigin.check refuses to options.deny, or returns 403, and passes one that matches a bypass pattern unchecked. Each Origin was checked when it was made, so the middleware itself cannot fail.

import std::http.{self, Body, CrossOrigin, Method, Request, Response, Route, Status}
import std::http::testing

pay = fn _: Request -> Response{body: Body.Text("paid")}
app = pay |> http.cross_origin_protection(CrossOrigin{bypass_patterns: ["POST /hooks/"]})

post = fn path: String -> {
    ..testing.request(Method.Post, path),
    headers: Headers[("Sec-Fetch-Site", "cross-site")],
}

assert app(post("/pay")).status == Status.forbidden
assert app(post("/hooks/stripe")).status == Status.ok
fn limit_body(handler: Handler, max: NonNegativeInt) -> (Request) -> Response

Middleware that limits each request’s body to max bytes (Request.limit_body), which lowers the server’s max_body or replaces the form readers’ defaults.

import std::http.{self, Body, Method, Request, Response}
import std::http::testing

upload = http.limit_body(fn r: Request -> Response{body: Body.Text("${r.body_limit}")}, 1_000)
assert Response.text(upload(testing.request(Method.Post, "/upload"))) == Ok("Some(1000)")
fn wrap_routes(routes: List<Entry>, wrap: (Handler) -> Handler) -> List<Entry>

routes with each handler wrapped by wrap, for applying middleware to a group of routes, such as every /admin route, before they join the others in one Router.

import std::http.{self, Body, Method, Request, Response, Route, Router, Status}
import std::http::testing

require_token = fn handler: Handler ->
    fn request: Request ->
        if Headers.get(request.headers, "Authorization") == Some("Bearer s3cret") then
            ToResponse.to_response(handler(request))
        else
            Response.error(Status.unauthorized, "unauthorized")
        end
    end
end

home = fn _: Request -> Response{body: Body.Text("home")}
users = fn _: Request -> Response{body: Body.Text("users")}

admin = [Route.to("GET /admin/users", users)]
routes = [Route.to("GET /", home)] + http.wrap_routes(admin, require_token)
router = Router.new(routes)!

assert Router.serve(router, testing.request(Method.Get, "/")).status == Status.ok

assert Router.serve(router, testing.request(Method.Get, "/admin/users")).status
    == Status.unauthorized
struct Cors
    origins: List<Origin> = []
    any_origin: Bool = False
    methods: List<Method> = [Method.Get, Method.Head, Method.Post]
    allowed_headers: List<String> = []
    exposed_headers: List<String> = []
    credentials: Bool = False
    max_age: Maybe<Duration> = None
end

Which cross-origin requests cors lets a browser make, and what it tells the browser about them. The defaults let no origin in.

impl Debug for Cors

fn inspect(value: Cors) -> String

impl Debug.inspect

fn cors(handler: Handler, options: Cors) -> (Request) -> Response

Middleware that handles CORS for the origins options allows, so a page on another origin, such as a frontend on its own host, can call the handler from a browser.

A preflight, an OPTIONS request with Origin and Access-Control-Request-Method, gets 204 No Content here and never reaches the handler. Any other request reaches it, and its response gets Access-Control-Allow-Origin with the request’s origin when that origin is allowed. A request from an origin that is not allowed gets no CORS headers, so the browser keeps the response from the page; the handler still runs, as it would for a form posted from that origin, so pair cors with cross_origin_protection or credentials checks for requests that change state. Every response gets Vary: Origin, so a cache does not hand one origin’s response to another.

import std::http.{self, Body, Cors, Method, Origin, Request, Response, Status}
import std::http::testing

api = fn _: Request -> Response{body: Body.Text("data")}

app =
    api
    |> http.cors(Cors{
        origins:         [Origin"https://app.example.com"],
        methods:         [Method.Get, Method.Post, Method.Delete],
        allowed_headers: ["Content-Type", "Authorization"],
    })

from = fn method: Method, origin: String -> {
    ..testing.request(method, "/api/items"),
    headers: Headers[("Origin", origin)],
}

ok = app(from(Method.Get, "https://app.example.com"))
assert Headers.get(ok.headers, "Access-Control-Allow-Origin") == Some("https://app.example.com")
assert Headers.get(ok.headers, "Vary") == Some("Origin")
assert Response.text(ok) == Ok("data")

refused = app(from(Method.Get, "https://evil.example"))
assert Headers.get(refused.headers, "Access-Control-Allow-Origin") == None
assert Response.text(refused) == Ok("data")

asking = from(Method.Options, "https://app.example.com")

preflight = app({..asking, headers: Headers.set(.., "Access-Control-Request-Method", "DELETE")})

assert preflight.status == Status.no_content

assert Headers.get(preflight.headers, "Access-Control-Allow-Methods") == Some("GET, POST, DELETE")

assert Headers.get(preflight.headers, "Access-Control-Allow-Headers")
    == Some("Content-Type, Authorization")
fn log_requests(handler: Handler, logger: Logger) -> (Request) -> Response

Middleware that writes one Info record to logger for each request, after the handler returns: request with the method, the path, the response’s status, duration_ms, the time the handler took, and bytes when the body’s length is known without reading it (a streamed body’s is not). A request that carries X-Request-Id adds it as request_id, so put request_id after log_requests in a pipe, outside it, to log the id it sets.

import std::http.{self, Body, Method, Request, Response, Status}
import std::http::testing as http_testing
import std::log
import std::log::testing as log_testing

hello = fn _: Request -> Response{status: Status.created, body: Body.Text("hello")}

got = log_testing.run(fn logger ->
    app = hello |> http.log_requests(logger) |> http.request_id()
    request = http_testing.request(Method.Post, "/items?x=1")
    app({..request, headers: Headers[("X-Request-Id", "req-7")]})
end)

record = List.first(got.records)!
assert record.message == "request"
assert List.contains(record.fields, log.string("method", "POST"))
assert List.contains(record.fields, log.string("path", "/items"))
assert List.contains(record.fields, log.int("status", 201))
assert List.contains(record.fields, log.int("bytes", 5))
assert List.contains(record.fields, log.string("request_id", "req-7"))
struct SecurityHeaders
    nosniff: Bool = True
    referrer_policy: Maybe<String> = Some("strict-origin-when-cross-origin")
    frame_options: Maybe<String> = Some("DENY")
    strict_transport_security: Maybe<String> = None
    content_security_policy: Maybe<String> = None
end

The headers security_headers adds to each response that does not set them itself. A None leaves that header out.

impl Debug for SecurityHeaders

fn inspect(value: SecurityHeaders) -> String

impl Debug.inspect

fn security_headers(handler: Handler, options: SecurityHeaders = SecurityHeaders{}) -> (Request) -> Response

Middleware that adds the headers options names to each response, as defaults: a header the handler set is kept. With no options it sends X-Content-Type-Options: nosniff, Referrer-Policy: strict-origin-when-cross-origin and X-Frame-Options: DENY.

import std::http.{self, Body, Method, Request, Response, SecurityHeaders}
import std::http::testing

page = fn r: Request ->
    if r.url.path == "/embed" then
        Response{headers: Headers[("X-Frame-Options", "SAMEORIGIN")]}
    else
        Response{body: Body.Text("page")}
    end
end

app = page |> http.security_headers()
plain = app(testing.request(Method.Get, "/"))
assert Headers.get(plain.headers, "X-Content-Type-Options") == Some("nosniff")
assert Headers.get(plain.headers, "Referrer-Policy") == Some("strict-origin-when-cross-origin")
assert Headers.get(plain.headers, "X-Frame-Options") == Some("DENY")
assert Headers.get(plain.headers, "Strict-Transport-Security") == None

assert Headers.get(app(testing.request(Method.Get, "/embed")).headers, "X-Frame-Options")
    == Some("SAMEORIGIN")

strict =
    page
    |> http.security_headers(SecurityHeaders{
        strict_transport_security: Some("max-age=63072000"),
        content_security_policy:   Some("default-src 'self'"),
    })

sent = strict(testing.request(Method.Get, "/"))
assert Headers.get(sent.headers, "Strict-Transport-Security") == Some("max-age=63072000")
assert Headers.get(sent.headers, "Content-Security-Policy") == Some("default-src 'self'")
fn request_id(handler: Handler, header: String = "X-Request-Id", trust_incoming: Bool = True) -> (Request) -> Response

Middleware that gives each request an id in header, X-Request-Id unless set, and sends it back on the response. It keeps an id the request came with when trust_incoming holds and the id is 1 to 128 letters, digits and -_.:+/=; otherwise it makes a random UUID. The handler reads the id from the request’s headers, and log_requests logs it when it runs inside request_id, before it in a pipe.

import std::http.{self, Body, Method, Request, Response}
import std::http::testing

echo = fn r: Request -> Response{body: Body.Text(Headers.get(r.headers, "X-Request-Id")!)}
app = echo |> http.request_id()

made = app(testing.request(Method.Get, "/"))
id = Headers.get(made.headers, "X-Request-Id")!
assert String.length(id) == 36
assert Response.text(made) == Ok(id)

given = fn id: String -> {
    ..testing.request(Method.Get, "/"),
    headers: Headers[("X-Request-Id", id)],
}

assert Headers.get(app(given("abc-123")).headers, "X-Request-Id") == Some("abc-123")
assert Headers.get(app(given("bad id\n")).headers, "X-Request-Id") != Some("bad id\n")

untrusting = echo |> http.request_id(trust_incoming: False)
assert Headers.get(untrusting(given("abc-123")).headers, "X-Request-Id") != Some("abc-123")
struct Compress
    min_size: Int = 1024
    level: Int = 6
end

How compress compresses.

impl Debug for Compress

fn inspect(value: Compress) -> String

impl Debug.inspect

fn compress(handler: Handler, options: Compress = Compress{}) -> (Request) -> Response

Middleware that compresses each response body with gzip when the request’s Accept-Encoding takes it (a coding it gives q=0 is refused), and adds Vary: Accept-Encoding to every response so a cache keeps the two forms apart. A compressed response gets Content-Encoding: gzip, loses its Content-Length, and has a strong ETag made weak (W/"..."), since its bytes are not the ones the tag names; If-None-Match still matches it.

A response is sent as it is when it already has a Content-Encoding (a precompressed file serve_embedded sends), has no body (1xx, 204, 304, a HEAD), is a range (206), says Cache-Control: no-transform, has a body known to be shorter than options.min_size, or has a content type that is compressed already: images other than SVG, audio, video, archives such as zip and gzip, and woff fonts. A body of bytes with no Content-Type gets the one its bytes are sniffed as first; a streamed body with none is sent as it is.

A Body.Stream is compressed as it is read, and a Body.Produce as it writes, each Writer.flush passing what it wrote so far to the client, so server-sent events still arrive one by one. Go’s standard library has no brotli encoder, so compress writes only gzip; serve .br files precompressed (serve_embedded).

import std::http.{self, Body, Method, Request, Response, Status}
import std::http::testing

page = String.repeat("<p>hello</p>", 200)
app = (fn _: Request -> Response{body: Body.Text(page)}) |> http.compress()

asking = fn accept: String ->
    r = testing.request(Method.Get, "/")
    {..r, headers: Headers[("Accept-Encoding", accept)]}
end

zipped = app(asking("gzip, br"))
assert Headers.get(zipped.headers, "Content-Encoding") == Some("gzip")
assert Headers.get(zipped.headers, "Content-Type") == Some("text/plain; charset=utf-8")
assert Headers.get(zipped.headers, "Vary") == Some("Accept-Encoding")
assert Bytes.length(Response.bytes(zipped)!) < 100
assert testing.decompressed(zipped) == Ok(String.to_bytes(page))

plain = app(asking("gzip;q=0, identity"))
assert Headers.get(plain.headers, "Content-Encoding") == None
assert Headers.get(plain.headers, "Vary") == Some("Accept-Encoding")
assert Response.text(plain) == Ok(page)

small = (fn _: Request -> Response{body: Body.Text("hi")}) |> http.compress()
assert Headers.get(small(asking("gzip")).headers, "Content-Encoding") == None
fn basic_auth(handler: Handler, realm: String, check: (String, String) -> Bool) -> (Request) -> Response

Middleware that lets a request through to handler only with a Basic Authorization header whose user and password check accepts. Any other request gets 401 Unauthorized with WWW-Authenticate: Basic realm="<realm>", charset="UTF-8", which has a browser ask for them. The handler reads the user with Request.basic_auth. Send it only over HTTPS: the password crosses in every request, encoded but not encrypted.

Write check with hash.equal_in_constant_time, never ==, which returns at the first byte that differs and so tells an attacker by its timing how much of a guess was right. Comparing SHA-256 digests keeps the lengths equal, so the time depends on neither, and checking both before combining them keeps a right user from showing either.

import std::hash
import std::http.{self, Body, Method, Request, Response, Status}
import std::http::testing

same = fn given: String, expected: String ->
    hash.equal_in_constant_time(
        hash.sha256(String.to_bytes(given)),
        hash.sha256(String.to_bytes(expected)),
    )
end

admin_only = fn user: String, password: String ->
    user_ok = same(user, "admin")
    password_ok = same(password, "s3cret")
    user_ok and password_ok
end

hello = fn r: Request -> Response{body: Body.Text("hello ${Request.basic_auth(r)!.first}")}
app = hello |> http.basic_auth("admin", admin_only)
visit = testing.request(Method.Get, "/admin")

refused = app(visit)
assert refused.status == Status.unauthorized

assert Headers.get(refused.headers, "WWW-Authenticate")
    == Some("Basic realm=\"admin\", charset=\"UTF-8\"")

assert app(Request.with_basic_auth(visit, "admin", "guess")).status == Status.unauthorized
assert Response.text(app(Request.with_basic_auth(visit, "admin", "s3cret"))) == Ok("hello admin")
fn method_override(handler: Handler) -> (Request) -> Response

Middleware that lets an HTML form, which can send only GET and POST, stand for a PUT, PATCH or DELETE: a POST whose URL-encoded body has a _method field naming one of those three, in any case, reaches handler as that method, so a router’s DELETE /posts/{id} route takes it. Any other request, and any other _method, passes as it came. The form is read up to the request’s body_limit, or 10 MB, and the handler can read it again; past the limit the request gets 413.

Wrap the router, so the method is changed before it routes, and put limit_body outside it (after it in a pipe) for its limit to hold here. The X-HTTP-Method-Override header is not read: a page on another origin could set it on a request a browser lets through.

import std::http.{self, Body, Method, Request, Response, Route, Router}
import std::http::testing

router = Router.new([
    Route.to("POST /posts", fn _ -> Response{body: Body.Text("created")}),
    Route.to_with("PATCH /posts/{id}", fn r, _ -> Response{
        body: Body.Text("titled ${Request.form_value(r, "title")!}"),
    }),
    Route.to_with("DELETE /posts/{id}", fn _, _ -> Response{body: Body.Text("deleted")}),
])!

app = Router.handler(router) |> http.method_override()

form = fn target: String, fields: List<(String, String)> ->
    testing.form_request(Method.Post, target, fields)
end

assert Response.text(app(form("/posts/7", [("_method", "delete")]))) == Ok("deleted")

assert Response.text(app(form("/posts/7", [("_method", "PATCH"), ("title", "Hi")])))
    == Ok("titled Hi")

assert Response.text(app(form("/posts", [("_method", "CONNECT")]))) == Ok("created")
fn serve_file(request: Request, file: String) -> Response

The file at path as the response to request, with ranges and conditional requests (Response.content). A directory is redirected to its path with a trailing slash, then served with its index.html or a listing of its entries; a request for .../index.html is redirected to ./.

When nothing is at file, the request’s path ends in no / and file does not end in .html, the page file.html is served in its place, as static hosts do: /about gets about.html, which is the file Next’s and SvelteKit’s static exports write for each route. The order is the file, then a directory, then the page. A request for /about.html is served that file as named, not redirected. Anything else missing is a 404, and a file that cannot be read a 403 or 500. Files come through std::fs, so std::fs::testing.run and fs.within apply.

import std::fs::testing as fs_testing
import std::fs::testing.Sandbox
import std::http.{Method, Response, Status}
import std::http::testing as http_testing

get = fn target: String, file: String -> serve_file(http_testing.request(Method.Get, target), file)

site = {"site/about.html" => "<p>about</p>", "site/blog/index.html" => "<p>blog</p>"}

ran = fs_testing.run(Sandbox{files: site}, fn ->
    (
        get("/about", "site/about"),
        get("/about.html", "site/about.html"),
        get("/blog", "site/blog"),
        get("/missing", "site/missing"),
    )
end)

(about, named, blog, missing) = ran.value
assert Response.text(about) == Ok("<p>about</p>")
assert Headers.get(about.headers, "Content-Type") == Some("text/html; charset=utf-8")
assert Response.text(named) == Ok("<p>about</p>")
assert blog.status == Status.moved_permanently
assert missing.status == Status.not_found
fn file_server(root: String, single_page: Bool = False) -> (Request) -> Response

A handler that serves each request the file under root its cleaned path names (serve_file).

A path that names no file or directory is tried with .html appended, so /about gets about.html (serve_file).

With single_page, a request for a page route that names no file, directory or .html page gets root’s index.html, status 200, so a single-page app whose client-side router owns /settings loads at that URL (is_page_route). A file that exists is served whatever its name, and a request for a missing asset is still a 404.

import std::fs::testing as fs_testing
import std::fs::testing.Sandbox
import std::http.{Method, Response, Status}
import std::http::testing as http_testing

site = file_server("site", single_page: True)
page = http_testing.request(Method.Get, "/settings")
page = {..page, headers: Headers.set(.., "Accept", "text/html")}

ran = fs_testing.run(Sandbox{files: {"site/index.html" => "<div id=root></div>"}}, fn ->
    (site(page), site(http_testing.request(Method.Get, "/app.js")))
end)

(shell, script) = ran.value
assert Response.text(shell) == Ok("<div id=root></div>")
assert script.status == Status.not_found
fn serve_embedded(request: Request, files: Files, file: String, immutable: List<String> = []) -> Response

serve_file from files a program embeds (std::embed): the file at file in files as the response to request, with its Content-Type from its name, ranges and conditional requests. A directory is redirected to its path with a trailing slash, then served with its index.html; one with no index.html is a 404, since an embedded tree is not listed. A request for .../index.html is redirected to ./. When nothing is at file, the request’s path ends in no / and file does not end in .html, the page file.html is served in its place, as serve_file serves it: the file, then a directory, then the page. Anything else missing is a 404.

The file’s SHA-256, which the compiler took when it read the file, is its strong ETag, so a request whose If-None-Match names it is a 304 with no body. A file whose path in files matches one of the immutable patterns (std::path’s matches: assets/** for every file under Vite’s assets, *-*.js for hashed scripts at the root) is sent with Cache-Control: public, max-age=31536000, immutable. Match only files that have their contents’ hash in their names, as a bundler writes them, since a browser keeps such a file for a year without asking again. A pattern with no wildcard (*, ? or [) names a file or a directory, and a directory covers every file under it, as in an embed pattern: assets is assets/**. Any other file is sent with Cache-Control: no-cache, which has a browser ask each time and get the 304 while the file is unchanged.

A file that has a precompressed sibling, file.br or file.gz as Vite’s and webpack’s compression plugins write them, is sent as that sibling when the request’s Accept-Encoding takes its coding (br first), with Content-Encoding, the original name’s Content-Type, and the sibling’s own ETag. Every response for such a file carries Vary: Accept-Encoding. Nothing is compressed while the program runs.

import std::http.{Method, Response, Status}
import std::http::testing

files = Files.from_bytes([
    ("index.html",                String.to_bytes("<p>home</p>")),
    ("assets/app-3f9a1b2c.js",    String.to_bytes("go()")),
    ("assets/app-3f9a1b2c.js.gz", String.to_bytes("zipped")),
])

get = testing.request(Method.Get, "/assets/app-3f9a1b2c.js")
js = serve_embedded(get, files, "assets/app-3f9a1b2c.js", immutable: ["assets/**"])
assert Headers.get(js.headers, "Cache-Control") == Some("public, max-age=31536000, immutable")
assert Headers.get(js.headers, "Content-Type") == Some("text/javascript; charset=utf-8")
assert Headers.get(js.headers, "Vary") == Some("Accept-Encoding")
assert Response.text(js) == Ok("go()")

gzip = {..get, headers: Headers.set(.., "Accept-Encoding", "gzip, deflate")}
zipped = serve_embedded(gzip, files, "assets/app-3f9a1b2c.js")
assert Headers.get(zipped.headers, "Content-Encoding") == Some("gzip")
assert Headers.get(zipped.headers, "Content-Type") == Some("text/javascript; charset=utf-8")
assert Response.text(zipped) == Ok("zipped")

home = serve_embedded(testing.request(Method.Get, "/"), files, ".")
etag = Headers.get(home.headers, "ETag")!
assert Headers.get(home.headers, "Cache-Control") == Some("no-cache")

again = testing.request(Method.Get, "/")
again = {..again, headers: Headers.set(.., "If-None-Match", etag)}
assert serve_embedded(again, files, ".").status == Status.not_modified

pages = Files.from_bytes([
    ("about.html",    String.to_bytes("<p>about</p>")),
    ("about.html.br", String.to_bytes("squeezed")),
])

about = serve_embedded(testing.request(Method.Get, "/about"), pages, "about")
assert Response.text(about) == Ok("<p>about</p>")
assert Headers.get(about.headers, "Content-Type") == Some("text/html; charset=utf-8")
assert Headers.get(about.headers, "Vary") == Some("Accept-Encoding")

brotli = testing.request(Method.Get, "/about")
brotli = {..brotli, headers: Headers.set(.., "Accept-Encoding", "br")}
squeezed = serve_embedded(brotli, pages, "about")
assert Headers.get(squeezed.headers, "Content-Encoding") == Some("br")
assert Response.text(squeezed) == Ok("squeezed")

slashed = serve_embedded(testing.request(Method.Get, "/about/"), pages, "about")
assert slashed.status == Status.not_found
fn file_server_embedded(files: Files, single_page: Bool = False, immutable: List<String> = []) -> (Request) -> Response

file_server over files a program embeds (std::embed): a handler that serves each request the file its cleaned path names in files (serve_embedded, which immutable is passed to). A path is cleaned before it is looked up, so no request reaches outside the tree. Serve a folder’s files at the root with Files.sub:

embed site `static`

fn static_files() -> (Request) -> Response
    http.file_server_embedded(Files.sub(site, "static")!)
end

A path that names no file or directory is tried with .html appended, so a static export with a page per route, about.html for /about, is served as written. With single_page, a request for a page route that names no file, directory or .html page gets the root index.html, status 200, as file_server serves it. A Vite build’s dist is served so:

embed web `web/dist`

fn frontend() -> (Request) -> Response
    http.file_server_embedded(
        Files.sub(web, "web/dist")!,
        single_page: True,
        immutable:   ["assets/**"],
    )
end
import std::http.{Method, Response, Status}
import std::http::testing

app = file_server_embedded(
    Files.from_bytes([
        ("index.html",             String.to_bytes("<div id=root></div>")),
        ("assets/app-3f9a1b2c.js", String.to_bytes("go()")),
    ]),
    single_page: True,
    immutable:   ["assets/**"],
)

visit = fn target: String ->
    r = testing.request(Method.Get, target)
    {..r, headers: Headers.set(.., "Accept", "text/html,*/*;q=0.8")}
end

assert Response.text(app(visit("/settings/profile"))) == Ok("<div id=root></div>")

exported = file_server_embedded(
    Files.from_bytes([
        ("index.html", String.to_bytes("<p>home</p>")),
        ("about.html", String.to_bytes("<p>about</p>")),
    ]),
    single_page: True,
)

assert Response.text(exported(visit("/about"))) == Ok("<p>about</p>")
assert Response.text(exported(visit("/contact"))) == Ok("<p>home</p>")
assert Response.text(app(visit("/users/jane.doe"))) == Ok("<div id=root></div>")

missing = testing.request(Method.Get, "/assets/gone-0a1b2c3d.js")
missing = {..missing, headers: Headers.set(.., "Accept", "*/*")}
assert app(missing).status == Status.not_found
fn is_page_route(request: Request) -> Bool

Whether request asks for a page a single-page app’s client-side router handles, which file_server and file_server_embedded respond to with index.html under single_page when no file matches the path: a GET or HEAD from a client that takes HTML, whose Accept names text/html. A browser sends that only when it navigates to a page, never for a script, stylesheet, image or fetch, so the path may hold a dot (/users/jane.doe) and a missing /assets/app.js stays a 404.

import std::http.Method
import std::http::testing

asked = fn method: Method, target: String, accept: String ->
    r = testing.request(method, target)
    {..r, headers: Headers.set(.., "Accept", accept)}
end

html = "text/html,application/xhtml+xml,*/*;q=0.8"
assert is_page_route(asked(Method.Get, "/settings/profile", html))
assert is_page_route(asked(Method.Get, "/users/jane.doe", html))
refute is_page_route(asked(Method.Get, "/assets/app.js", "*/*"))
refute is_page_route(asked(Method.Post, "/settings", html))
refute is_page_route(asked(Method.Get, "/api/users", "application/json"))
refute is_page_route(asked(Method.Get, "/api/users", "*/*"))
fn detect_content_type(data: Bytes) -> String

The media type of data, guessed from at most its first 512 bytes by the WHATWG MIME sniffing rules, as Go’s DetectContentType guesses it: text/plain; charset=utf-8 for text, application/octet-stream when nothing matches.

assert http.detect_content_type(String.to_bytes("<html>")) == "text/html; charset=utf-8"
fn format_time(at: Instant) -> String

at as HTTP headers write dates, in GMT: Mon, 02 Jan 2006 15:04:05 GMT.

import std::instant.Instant

assert http.format_time(Instant.from_seconds(0)) == "Thu, 01 Jan 1970 00:00:00 GMT"
fn parse_time(text: String) -> Result<Instant, Error>

A date in any of the three formats HTTP allows: the one format_time writes, RFC 850’s and ANSI C’s asctime, of any year, such as the Fri, 31 Dec 9999 23:59:59 GMT servers send for “never”. Text in none of them is Error.Protocol.

enum SameSite
    Unset
    Default
    Lax
    Strict
    None
end

A cookie’s SameSite attribute.

Variants

  • Unset

    No attribute.

  • Default

    SameSite with no value.

  • None

    SameSite=None, which browsers accept only with secure.

impl Debug for SameSite

fn inspect(value: SameSite) -> String

impl Debug.inspect

impl Equatable for SameSite

fn equal(a: SameSite, b: SameSite) -> Bool

impl Equatable.equal

enum MaxAge
    Unset
    DeleteNow
    Seconds Int
end

A cookie’s Max-Age, in place of Go’s 0 and negative codes.

Variants

  • Unset

    No Max-Age attribute.

  • DeleteNow

    Max-Age=0: delete the cookie now.

impl Debug for MaxAge

fn inspect(value: MaxAge) -> String

impl Debug.inspect

impl Equatable for MaxAge

fn equal(a: MaxAge, b: MaxAge) -> Bool

impl Equatable.equal

struct Cookie
    name: String
    value: String
    quoted: Bool = False
    path: Maybe<String> = None
    domain: Maybe<String> = None
    expires: Maybe<Instant> = None
    raw_expires: Maybe<String> = None
    max_age: MaxAge = MaxAge.Unset
    secure: Bool = False
    http_only: Bool = False
    same_site: SameSite = SameSite.Unset
    partitioned: Bool = False
    raw: Maybe<String> = None
    unparsed: List<String> = []
end

An HTTP cookie: what a Set-Cookie header sets or a Cookie header sends. raw_expires, raw and unparsed are set by parsing only. A parsed expiry of any year (the year 9999 is common for “never”) is expires; one Go cannot parse leaves expires None and is kept in raw_expires.

fn parse_header(text: String) -> Result<List<Cookie>, Error>

type function on Cookie

The cookies of a Cookie header’s value, as Go’s ParseCookie.

import std::http.Cookie

names = Cookie.parse_header("a=1; b=2")! |> Iter.map(fn c -> c.name) |> Iter.to_list()
assert names == ["a", "b"]
fn parse_set_cookie(text: String) -> Result<Cookie, Error>

type function on Cookie

The cookie of a Set-Cookie header’s value, as Go’s ParseSetCookie.

import std::http.{Cookie, MaxAge}

c = Cookie.parse_set_cookie("id=7; Path=/; Max-Age=60; Secure")!
assert c.path == Some("/")
assert c.max_age == MaxAge.Seconds(60)
assert c.secure
fn validate(cookie: Cookie) -> Result<Unit, Error>

type function on Cookie

Ok when the cookie can be written in a Set-Cookie header: its name is a token, and its value, path, domain and expiry hold only what the header allows, and a partitioned cookie is secure. Otherwise Error.Protocol says what is wrong.

impl Display for Cookie

fn to_string(cookie: Cookie) -> String

impl Display.to_string

impl Debug for Cookie

fn inspect(value: Cookie) -> String

impl Debug.inspect

impl Equatable for Cookie

fn equal(a: Cookie, b: Cookie) -> Bool

impl Equatable.equal

struct CookieJar
    handle: http_host.Jar
end

Where a client keeps cookies: Go’s net/http/cookiejar, with no public suffix list. Give it to a client with ClientOptions.cookies.

fn new() -> CookieJar

type function on CookieJar

An empty jar.

fn cookies(jar: CookieJar, url: Url) -> List<Cookie>

type function on CookieJar

The cookies the jar would send with a request to url.

import std::http.{Cookie, CookieJar}
import std::url.Url

jar = CookieJar.new()
CookieJar.set_cookies(jar, Url"https://example.com/", [Cookie{name: "a", value: "1"}])

sent =
    CookieJar.cookies(jar, Url"https://example.com/x") |> Iter.map(fn c -> c.name) |> Iter.to_list()

assert sent == ["a"]
fn set_cookies(jar: CookieJar, url: Url, cookies: List<Cookie>) -> Unit

type function on CookieJar

Stores cookies, as received in a response from url.

impl Debug for CookieJar

fn inspect(value: CookieJar) -> String

impl Debug.inspect

enum ConnState
    New
    Active
    Idle
    Hijacked
    Closed
end

What a server’s connection is doing: Go’s ConnState.

impl Display for ConnState

fn to_string(state: ConnState) -> String

impl Display.to_string

import std::http.ConnState

assert "${ConnState.Idle}" == "idle"

impl Debug for ConnState

fn inspect(value: ConnState) -> String

impl Debug.inspect

impl Equatable for ConnState

fn equal(a: ConnState, b: ConnState) -> Bool

impl Equatable.equal

fn serve_here(listener: Listener, handler: Handler) -> Unit

Serves each request listener receives with handler, each as a task of a concurrent block of its own, and returns once the listener shuts down and every request it took is served. For a server with no supervisor, as in a test; a program’s server uses serve and a supervisor, whose max_running bounds the requests in flight.

struct ProxyRequest
    incoming: Request
    outgoing: Request
end

The request a reverse proxy received and the request it will send, for its rewrite function: Go’s ProxyRequest.

fn set_url(proxy: ProxyRequest, target: Url) -> ProxyRequest

type function on ProxyRequest

Sends the outgoing request to target: its scheme and host, its path joined before the request’s, its query before the request’s. The Host sent is the target’s. Go’s SetURL.

fn set_x_forwarded(proxy: ProxyRequest) -> ProxyRequest

type function on ProxyRequest

Sets X-Forwarded-For to the client’s address (added to what an earlier proxy set), X-Forwarded-Host to the host it asked for and X-Forwarded-Proto to http or https. Go’s SetXForwarded.

impl Debug for ProxyRequest

fn inspect(value: ProxyRequest) -> String

impl Debug.inspect

struct ReverseProxy
    rewrite: (ProxyRequest) -> ProxyRequest
    client: Client = default_client()
    modify_response: Maybe<(Response) -> Result<Response, Error>> = None
    on_error: Maybe<(Request, Error) -> Response> = None
    flush_interval: Maybe<Duration> = None
    on_error_log: Maybe<(String) -> Unit> = None
end

How a reverse proxy forwards: Go’s ReverseProxy. rewrite turns each request it receives into the one it sends.

fn to(target: Url) -> ReverseProxy

type function on ReverseProxy

A proxy to one host: each request goes to target, its path joined after the target’s, with X-Forwarded-* set. Go’s NewSingleHostReverseProxy.

impl Debug for ReverseProxy

fn inspect(value: ReverseProxy) -> String

impl Debug.inspect

fn reverse_proxy(options: ReverseProxy) -> (Request) -> Response

A handler that forwards each request as options says and responds with the response, its connection headers removed: Go’s ReverseProxy.ServeHTTP. The response streams to the client as it arrives, flushed as flush_interval says.

struct Tracer
    handle: http_host.Handle
end

Records what Go’s client reports while it sends the requests that name it in Request.trace: Go’s httptrace.ClientTrace, as data rather than callbacks.

fn new() -> Tracer

type function on Tracer

A tracer that has recorded nothing. A request names it in its trace field.

fn events(tracer: Tracer) -> List<TraceEvent>

type function on Tracer

What happened so far, in order.

impl Debug for Tracer

fn inspect(value: Tracer) -> String

impl Debug.inspect

enum TraceEvent
    GetConnection { address: String }
    GotConnection { reused: Bool, was_idle: Bool, idle_time: Duration }
    PutIdleConnection { error: Maybe<String> }
    FirstResponseByte
    Continue
    Informational { status: Status, headers: Headers }
    DnsStart { host: String }
    DnsDone { addresses: List<String>, error: Maybe<String>, coalesced: Bool }
    ConnectStart { network: String, address: String }
    ConnectDone { network: String, address: String, error: Maybe<String> }
    TlsStart
    TlsDone { state: tls.ConnectionState, error: Maybe<String> }
    WroteHeader { name: String, values: List<String> }
    WroteHeaders
    WaitContinue
    WroteRequest { error: Maybe<String> }
end

One thing a client did while it sent a request: Go’s ClientTrace hooks, each with its info’s fields.

Variants

  • GetConnection

    It looked for a connection to address (host:port).

  • GotConnection

    It got one: reused from an earlier request, idle for idle_time.

  • PutIdleConnection

    It returned the connection to the idle pool, or failed to.

  • Continue

    The server sent 100 Continue.

  • Informational

    The server sent a 1xx status before the final one.

  • WroteHeader

    It wrote one header field.

  • WaitContinue

    It waits for 100 Continue before sending the body.

impl Debug for TraceEvent

fn inspect(value: TraceEvent) -> String

impl Debug.inspect

fn chunked_reader(r: Reader) -> Reader

A reader of the chunked transfer coding over r, which ends at the last, empty chunk: httputil’s NewChunkedReader.

import std::http
import std::io.Reader

r = http.chunked_reader(Reader.from_text("2\r\nhi\r\n0\r\n\r\n"))
assert Reader.read_all_text(r) == Ok("hi")
fn chunked_writer(w: Writer) -> Writer

A writer that sends what it is given to w in the chunked transfer coding; closing it writes the last, empty chunk and leaves w open: httputil’s NewChunkedWriter.

struct Part
    headers: Headers
    body: Reader
    handle: http_host.Handle
end

One part of a multipart body, read as it arrives: Go’s multipart.Part. Reading the next part ends this one.

fn form_name(part: Part) -> Maybe<String>

type function on Part

The name of its form-data Content-Disposition, if any.

fn file_name(part: Part) -> Maybe<String>

type function on Part

The filename of its Content-Disposition, if any.

impl Debug for Part

fn inspect(value: Part) -> String

impl Debug.inspect

fn multipart_parts(r: Reader, boundary: String) -> Iter<Result<Part, Error>>

The parts of the multipart body r holds, separated by boundary, each read as the iteration reaches it: Go’s multipart.NewReader and its NextPart, which decodes quoted-printable parts. An Err ends it.

import std::http
import std::http.Part
import std::io.Reader

body = "--b\r\nContent-Disposition: form-data; name=\"a\"\r\n\r\none\r\n--b--\r\n"

names =
    http.multipart_parts(Reader.from_text(body), "b")
    |> Iter.map(fn p -> p |> Result.map(Part.form_name))
    |> Iter.to_list()

assert names == [Ok(Some("a"))]
fn multipart_raw_parts(r: Reader, boundary: String) -> Iter<Result<Part, Error>>

multipart_parts with each part as it was sent, not decoded: Go’s NextRawPart.

fn read_multipart_form(r: Reader, boundary: String, max: Int = 33_554_432) -> Result<MultipartForm, Error>

The multipart form r holds, read whole: Go’s Reader.ReadForm. A form larger than max bytes is Error.BodyTooLarge; no more than one byte past max is read.

fn write_multipart(w: Writer, boundary: String, parts: List<FormPart>) -> Result<Unit, Error>

Writes parts to w as a multipart body separated by boundary, each as it comes, then the closing boundary: Go’s multipart.Writer. The body’s Content-Type is multipart/form-data; boundary= and the boundary.