http reference
The http package: http.
http
class App
offer class AppRoutes and the layers around them.
field router
var router: Routerfield layers
var layers: Layersfield limits
var limits: Limitsmethod Get
fun Get(pattern: text, handle: keep fun(Request) -> Response) uses unsafeA route for GET. The same names a router has, so an application
can be built without reaching inside it.
method Post
fun Post(pattern: text, handle: keep fun(Request) -> Response) uses unsafemethod Put
fun Put(pattern: text, handle: keep fun(Request) -> Response) uses unsafemethod Patch
fun Patch(pattern: text, handle: keep fun(Request) -> Response) uses unsafemethod Delete
fun Delete(pattern: text, handle: keep fun(Request) -> Response) uses unsafemethod Any
fun Any(pattern: text, handle: keep fun(Request) -> Response) uses unsafemethod Otherwise
fun Otherwise(handle: keep fun(Request) -> Response) uses unsafemethod Mount
fun Mount(prefix: text, inner: &Router) uses unsafemethod Use
fun Use(run: keep fun(&mut Request) -> Response?) uses unsafeA layer that runs before every handler, and may answer instead.
method Then
fun Then(run: keep fun(&Request, Response) -> Response) uses unsafeA layer that runs after every handler.
function AppNew
offer fun AppNew() -> App uses unsafefunction ServeApp
offer fun ServeApp(app: App, port: int, most: int) -> s32 uses io, net, time, unsafeServes app on port until the program stops.
Serve is taken by the one-connection loop, so the application's
entry point says what it serves.
most connections at once, each with a buffer of its own.
function ServeWithDefaults
offer fun ServeWithDefaults(app: App, port: int, most: int) -> s32 uses io, net, time, unsafeThe same, with the usual layers already on: a line per request, the security headers, and CORS.
What a program that has not decided anything yet should call, because every one of those is something a server wants and none of them is something a handler should have to remember.
function ServeMany
offer fun ServeMany(app: App, port: int, most: int, threads: int) -> s32 uses io, net, time, unsafeServes app on port from threads threads at once.
Zero threads means one per core. Every thread runs the same
application: a handler that keeps state in a module-level var is
sharing it across threads, and whether that is safe is the program's
business -- a counter wants std.thread.AtomicAdd and a table wants
a Mutex (D135).
error BadUrl
offer error BadUrl, NeedsTls, Unreachable, Truncated, NotHttpstruct Url
offer struct UrlA URL taken apart.
field host
var host: text = ""field port
var port: int = 80field target
var target: text = "/"The path and the query together, which is what a request line carries.
field secure
var secure: bool = falsefunction ParseUrl
offer fun ParseUrl(url: text) -> Url!BadUrl uses unsafehttp://host:port/path?query taken apart.
struct Reply
offer struct ReplyWhat came back. Reply rather than Answer, because a server's
answer is already called that (D144).
field status
var status: int = 0field body
var body: text = ""field headers
var headers: [24]Pairfield header_count
var header_count: int = 0function ReplyHeader
offer fun ReplyHeader(answer: &Reply, name: text, fallback: text) -> text uses unsafeThe header called name, or fallback. Case does not matter.
function Fetch
offer fun Fetch(url: text) -> Reply!(BadUrl, Unreachable, Truncated, NotHttp) uses io, net, time, unsafeGET url.
function PostJson
offer fun PostJson(url: text, body: text) -> Reply!(BadUrl, Unreachable, Truncated, NotHttp) uses io, net, time, unsafePOST url with a JSON body.
function PutJson
offer fun PutJson(url: text, body: text) -> Reply!(BadUrl, Unreachable, Truncated, NotHttp) uses io, net, time, unsafePUT, PATCH and DELETE, for an API that uses them.
function PatchJson
offer fun PatchJson(url: text, body: text) -> Reply!(BadUrl, Unreachable, Truncated, NotHttp) uses io, net, time, unsafefunction Delete
offer fun Delete(url: text) -> Reply!(BadUrl, Unreachable, Truncated, NotHttp) uses io, net, time, unsafefunction PostForm
offer fun PostForm(url: text, body: text) -> Reply!(BadUrl, Unreachable, Truncated, NotHttp) uses io, net, time, unsafeA form submission: a=1&b=two, escaped, as a browser sends it.
function Perform
offer fun Perform(call: Call) -> Reply!(BadUrl, Unreachable, Truncated, NotHttp) uses io, net, time, unsafeWhat a built call does. Perform, because Request is what a
server receives and Run is what a server does.
Redirects are followed up to the call's limit -- a 303 becomes a
GET with no body, which is what the status means and what every
other client does -- and https goes over the system's TLS (D151).
function Absolute
offer fun Absolute(from: text, location: text) -> text uses unsafeA Location resolved against where the request went.
Absolute stays as it is; /path keeps the host; anything else is
relative to the directory the request was in.
function Once
offer fun Once(call: Call) -> Reply!(BadUrl, Unreachable, Truncated, NotHttp) uses io, net, time, unsafeOne request, one answer, no redirects.
Connection: close on the way out, because a client that holds a
connection has to decide when to let it go -- and a function that
answers once has nowhere to keep it. A client that wants keep-alive
uses Open and Ask.
function Written
offer fun Written(call: Call, target: Url, keep_alive: bool) -> text uses unsafeThe bytes of a request.
function Open
offer fun Open(url: text) -> Socket!(BadUrl, NeedsTls, Unreachable) uses io, net, unsafeA connection held open, for a program making several calls.
Plain only: a kept TLS connection is tls.Open and Ask over it,
which a caller that wants one can write in three lines.
function Ask
offer fun Ask(
connection: &mut Socket,
target: Url,
method: text,
body: text,
kind: text,
keep_alive: bool) -> Reply!(Unreachable, Truncated, NotHttp) uses io, time, unsafeOne request on a connection the caller owns. One request on a connection the caller owns.
function Plain
offer fun Plain(connection: &mut Socket, timeout: int) -> Reply!(Truncated, NotHttp) uses io, time, unsafeReads an answer off a plain connection.
function Secure
offer fun Secure(stream: &mut Stream, timeout: int) -> Reply!(Truncated, NotHttp) uses io, time, unsafeThe same, over TLS.
The same loop twice rather than one loop over an ability: a stream and a socket are two types with the same three methods, and an ability with a method per direction is more machinery than the duplication costs (D151).
function Progress
offer fun Progress(
received: &mut Builder,
head: &mut int,
length: &mut int,
chunked: &mut bool) -> bool uses unsafeWhether what has arrived is the whole answer.
The head first -- which says how the body is framed -- and then
either Content-Length bytes or chunks up to the empty one. A read
stops wherever it likes, which is why this is asked after every one.
function Finish
offer fun Finish(whole: text, head: int, length: int, chunked: bool) -> Reply!(Truncated, NotHttp) uses unsafeThe answer, with a chunked body put back together.
function ChunkedEnd
offer fun ChunkedEnd(whole: text, head: int) -> int uses unsafeWhere a chunked body ends, or -1 when it has not yet.
function FromHexDigits
offer fun FromHexDigits(line: text) -> int uses unsafeThe number a hexadecimal chunk header spells, or -1.
More than seven digits is -1: eight would overflow int and trap the
client on a hostile server's chunk header (D223).
A header may carry extensions after a ;, which nothing uses and
everything has to skip.
function IsChunked
offer fun IsChunked(head: text) -> bool uses unsafeWhether the head says the body comes in chunks.
function ParseReply
offer fun ParseReply(whole: text, head: int, length: int) -> Reply!NotHttp uses unsafeWhat a response's bytes mean.
function ReplyNew
offer fun ReplyNew() -> ReplyAn empty answer, to fill in.
constant kStartingRoom
offer const kStartingRoom: int = 8192How big one connection's buffer starts out, and how far it may grow.
struct Limits
offer struct LimitsWhat a server will not read past, per request.
field most_request
var most_request: int = 1048576The whole request: head and body together.
field most_head
var most_head: int = 16384The head on its own, which is what stops a client from sending headers forever.
field keep_alive
var keep_alive: bool = trueWhether a connection is kept open after an answer.
field head_timeout
var head_timeout: int = 10Seconds a connection may take to deliver a request, counted from its first byte (or from the accept, before it has sent any). What stops a client that trickles one header byte at a time from holding a slot for ever (D223).
field idle_timeout
var idle_timeout: int = 60Seconds a keep-alive connection may sit between requests.
function LimitsDefault
offer fun LimitsDefault() -> Limitsstruct Held
offer struct HeldWhere one connection's bytes are kept.
field fd
var fd: int = -1field buffer
var buffer: []mut u8field filled
var filled: int = 0field closing
var closing: bool = falseSet when the client said Connection: close, or when the server
decided this one is done: the loop closes it after answering.
field since
var since: s64 = 0When the wait for the current request began, in monotonic seconds: the accept, the end of the last answer, or the first byte of this request, whichever is latest (D223).
field served
var served: bool = falseWhether this connection has had a request answered. Until then it owes the head deadline even with nothing sent.
function IsExpired
offer fun IsExpired(
now: s64,
since: s64,
partial: bool,
served: bool,
limits: Limits) -> boolWhether a connection that has waited since since has used up its
time at now. Pure, so the rule is testable without a clock or a
socket (D223).
A connection with part of a request in its buffer, or one that has not yet had any request answered, is on the short head deadline; one that is idle between keep-alive requests gets the long one.
class Connections
offer class ConnectionsA pool of connection buffers, one slot per connection held at once.
field slots
var slots: []mut Heldfield limits
var limits: Limitsmethod deinit
deinitmethod Find
fun Find(fd: int) -> intThe slot fd is in, or -1.
method Open
fun Open(fd: int) -> int uses unsafeTakes a slot for fd, or -1 when the pool is full.
A full pool is the server's back pressure: the caller closes the connection rather than accepting work it has nowhere to put.
method Release
fun Release(slot: int)Gives the slot back. The buffer stays for the next connection: a server that allocates per connection allocates per request under load.
method Stamp
fun Stamp(slot: int, now: s64)Starts the slot's wait for a request at now.
method MarkServed
fun MarkServed(slot: int)Notes that a request on this slot was answered.
method TimedOut
fun TimedOut(slot: int, now: s64) -> boolWhether the slot holds a connection that has waited too long.
method Fd
fun Fd(slot: int) -> intmethod IsClosing
fun IsClosing(slot: int) -> boolmethod SetClosing
fun SetClosing(slot: int, closing: bool)method Filled
fun Filled(slot: int) -> intmethod Reserve
fun Reserve(slot: int, wanted: int) -> bool uses unsafeMakes room for wanted bytes in a slot's buffer, up to the limit.
False when the request wants more than the server allows, which the
caller answers with 413 rather than by growing.
method Room
fun Room(slot: int) -> intWhere to read into, and how much room is there.
method Fill
fun Fill(slot: int) -> int uses unsafeReads once from the connection into its buffer. How many bytes arrived, zero when nothing was waiting, or negative when the connection is finished.
method Bytes
fun Bytes(slot: int) -> []u8The bytes a slot holds.
method Consume
fun Consume(slot: int, count: int)Takes count bytes off the front, keeping what came after.
What makes pipelining work: two requests in one read are two turns, and the second one's bytes are still here for the next.
function ConnectionsNew
offer fun ConnectionsNew(most: int, limits: Limits) -> Connections uses unsafefunction RequestLength
offer fun RequestLength(bytes: []u8, filled: int, limits: Limits) -> int uses unsafeHow long a request is, or what is missing.
-1 says "not all here yet", -2 says "this is not a request",
-3 says "bigger than the server allows", and -4 says "it frames
its body in a way this server does not implement" (D223).
function HeadEnd
offer fun HeadEnd(bytes: []u8, filled: int) -> intWhere the blank line that ends the head is, or -1.
function HeaderIn
offer fun HeaderIn(bytes: []u8, head: int, name: text) -> text uses unsafeOne header's value out of raw bytes, before anything is parsed.
Used for the two headers the loop itself needs -- the length and
whether to keep the connection -- which have to be read before there
is a Request to ask (D122).
function ValueAt
offer fun ValueAt(bytes: []u8, head: int, start: int) -> text uses unsafeThe value that starts at start, up to the end of its line.
function HeaderStart
offer fun HeaderStart(bytes: []u8, head: int, name: text, skip: int) -> int uses unsafeWhere the value of the skipth header called name (counting from
zero) starts, or -1 when there are not that many: a repeated
Content-Length has to be seen to be compared (D223). An index rather
than an optional text, so that an empty value is not "absent".
function QueryInt
offer fun QueryInt(request: &Request, name: text, fallback: int) -> int uses unsafeThe query parameter called name as a number, or fallback.
function QueryBool
offer fun QueryBool(request: &Request, name: text, fallback: bool) -> bool uses unsafeThe query parameter as a flag: true, 1, yes and on are true.
function ParamInt
offer fun ParamInt(request: &Request, name: text, fallback: int) -> int uses unsafeThe path parameter called name as a number.
function QueryText
offer fun QueryText(request: &Request, name: text, fallback: text) -> text uses unsafeThe query parameter with %20 and + read back.
function ParseSigned
offer fun ParseSigned(value: text, fallback: int) -> int uses unsafeA number, with a sign, or fallback when it is not one.
ParseInt in this package stops at the first byte that is not a
digit, which is what a Content-Length deserves and not what a query
parameter does: page=x should mean "no number here" rather than
zero.
function ContentType
offer fun ContentType(request: &Request) -> text uses unsafeWhat the request says its body is.
function IsJson
offer fun IsJson(request: &Request) -> bool uses unsafeWhether the body says it is JSON.
function JsonBody
offer fun JsonBody(request: &Request) -> Value!json.Malformed uses unsafeThe body as JSON, or the error the parser gave.
A handler that wants to answer 400 rather than 500 for a bad
document matches on this: the body came from outside, so "this is not
JSON" is an answer and not a fault.
function Field
offer fun Field(request: &Request, name: text, fallback: text) -> text uses unsafeThe field called name from a form-encoded body.
a=1&b=two, which is what a browser form sends: the same shape as a
query string, so the same walk with the escapes read back.
function Bearer
offer fun Bearer(request: &Request) -> text uses unsafeThe token from Authorization: Bearer <token>, or "".
function Cookie
offer fun Cookie(request: &Request, name: text, fallback: text) -> text uses unsafeThe cookie called name, or fallback.
One header with a=1; b=2 in it, which is how a browser sends them.
function Accepts
offer fun Accepts(request: &Request, kind: text) -> bool uses unsafeWhether the client said it would take kind.
A plain substring search rather than a full parse of the header's
weights: a handler asking "will this client take JSON" wants a yes or
a no, and */* is a yes.
function TypeOf
offer fun TypeOf(path: text) -> text uses unsafeWhat a browser should make of a file, by its extension.
constant kMostBytes
offer const kMostBytes: int = 8388608How much of one file this will read. A server that serves a video wants ranges, which is a different protocol.
function ServeFile
offer fun ServeFile(path: text) -> Response uses io, unsafeThe file at path, as a response.
404 when it is not there, which is the same answer as "you may not
have it": a server that says "no such file" for one path and
"forbidden" for another has told the asker which files exist.
function IsServable
offer fun IsServable(relative: text) -> bool uses unsafeWhether name is something a server should hand out at all.
Not a dotfile -- .env and .git are the two every leak is made of
-- and nothing with a .. left in it after normalizing.
function ServeUnder
offer fun ServeUnder(root: text, request: &Request, prefix: text) -> Response uses io, unsafeThe file under root that request asked for.
The path is taken from what the router matched for *, or from the
request path with prefix removed. Everything about it is checked:
the escapes are read back, the dots are worked out, dotfiles are
refused, and the answer has to still be inside root.
function ServeOr
offer fun ServeOr(root: text, request: &Request, prefix: text, fallback: text) -> Response uses io, unsafeThe one file a single-page application wants for every path it does not have a file for.
struct Pair
offer struct PairOne name and one value: a header, a query parameter, a path parameter. The same shape for all three, because the work -- find the one called this -- is the same (D112).
field name
var name: text = ""field value
var value: text = ""constant kMostHeaders
offer const kMostHeaders: int = 24constant kMostParams
offer const kMostParams: int = 8struct Request
offer struct RequestA request, as views into the buffer it was read from.
Everything here is a view: the bytes stay in the connection's buffer until the turn is over, which is what makes reading a request cost no allocation at all.
field method
var method: text = ""field path
var path: text = ""field query
var query: text = ""field body
var body: text = ""field headers
var headers: [24]Pairfield header_count
var header_count: int = 0field params
var params: [8]Pairfield param_count
var param_count: int = 0field length
var length: int = 0field http_11
var http_11: bool = truefunction RequestNew
offer fun RequestNew() -> RequestAn empty request, to fill in.
The arrays are not written here: an element nobody filled is never read, because the counts say how many there are.
constant kMostAnswerHeaders
offer const kMostAnswerHeaders: int = 8What a handler answers with.
Its headers are a fixed run for the same reason a request's are: a response is built, handed on and written, and a list that owns its storage would make every one of those a question about who frees it (D112).
struct Response
offer struct Responsefield status
var status: intfield body
var body: textfield kind
var kind: textfield headers
var headers: [8]Pairfield header_count
var header_count: intfunction Header
offer fun Header(request: &Request, name: text, fallback: text) -> text uses unsafeThe value of the header called name, or fallback.
Compared without regard to case, because a client may send
Content-Type or content-type and both mean the same header.
function Query
offer fun Query(request: &Request, name: text, fallback: text) -> text uses unsafeThe query parameter called name, or fallback.
?a=1&b=two is read on demand rather than up front: most handlers
want one of them, and splitting the rest costs a pass over bytes
nobody reads.
function Param
offer fun Param(request: &Request, name: text, fallback: text) -> text uses unsafeThe path parameter called name, or fallback: what the router
matched for :name.
function Ok
offer fun Ok(body: text) -> Response200 OK, as plain text.
function OkJson
offer fun OkJson(body: text) -> Response200 OK, as a JSON document. The body is written as it is: a handler
that has a Json value writes it with json.Write first.
function Created
offer fun Created(location: text, body: text) -> Response201 Created, with where the thing was created.
function NoContent
offer fun NoContent() -> Responsefunction NotFound
offer fun NotFound() -> Responsefunction BadRequest
offer fun BadRequest(why: text) -> Responsefunction Status
offer fun Status(status: int, body: text) -> Responsefunction WithHeader
offer fun WithHeader(answer: Response, name: text, value: text) -> ResponseThe same response with one more header on it. Answers the response, so calls chain.
function WithType
offer fun WithType(answer: Response, kind: text) -> ResponseThe same response with a different content type.
function ParseRequest
offer fun ParseRequest(everything: []u8, received: int) -> Request uses unsafeSplits GET /path HTTP/1.1 into its first two words.
Returns a request whose length is zero when the line is not one: a
parser that cannot say "this is not a request" is not a parser.
Only the first received bytes are looked at: the buffer is reused
from one client to the next, and what lies past received belongs to
whoever used it before (D223).
function ParseInt
offer fun ParseInt(value: text) -> int uses unsafeThe number value spells, or zero. Stops at the first byte that is
not a digit, which is what a Content-Length with anything after it
deserves. More than nine digits is -1. Nine digits is this parser's own cap,
not the width of int (64 bits, D238); it keeps total * 10 far from
overflow (D223).
function ParseLength
offer fun ParseLength(value: text) -> int uses unsafeThe number a Content-Length spells, or -1 when it spells anything
else: no digits, or garbage such as 5, 10. Spaces and tabs around
the digits are allowed. A run of more than nine digits is a length, but
no server's: it answers 2147483647, the largest s32 and a cap this
parser keeps although int is 64 bits (D238), which every limit refuses
with 413 rather than the 400 that garbage gets (D223).
function Serve
offer fun Serve(connection: s32, handle: fun(Request) -> Response) -> int uses io, net, time, unsafeServes a connection until the client stops asking.
One request per turn, each inside an arena of its own: everything a request allocates -- its response, the strings it interpolated -- comes from there and goes back at the end of the turn. Keep-alive is what makes that worth doing, because the connection outlives the arena.
function ServeWith
offer fun ServeWith(
connection: s32,
handle: fun(Request) -> Response,
limits: Limits) -> int uses io, net, time, unsafeThe same, with limits of the caller's choosing.
One connection, served until the client stops asking or breaks the
rules: every request is read whole before the handler sees it, and
what arrived after it stays for the next turn (D122). A client that
says nothing for longer than limits.head_timeout, or
limits.idle_timeout between requests, is closed (D223).
function Turn
offer fun Turn(
pool: &mut Connections,
slot: int,
handle: fun(Request) -> Response) -> int uses io, net, time, unsafeOne turn on one connection: read what is there, answer every whole request in it, and say whether the connection is still worth holding.
1 when a request was answered, 0 when more is wanted, and -1
when the connection is finished. A server that polls calls this once
per readable connection; a blocking one calls it in a loop.
function WriteResponse
offer fun WriteResponse(connection: s32, answer: Response) -> bool uses io, net, time, unsafeWrites a response: the status line, the headers it carries, and the body.
One write, because two writes of a small response wait for each other on a socket -- the second is held back until the first is acknowledged -- which costs more than building the string does.
function WriteAnswer
offer fun WriteAnswer(
connection: s32,
answer: Response,
with_body: bool,
keep_alive: bool) -> bool uses io, net, time, unsafeThe same, told whether to write the body and whether the connection stays open.
A HEAD is a GET whose body is not written -- the length still says
what it would have been, which is the whole point of asking -- and a
client that said Connection: close is told the server agrees before
the socket goes away (D122).
function Date
offer fun Date() -> text uses time, unsafeThe date header, in the format HTTP wants.
function Run
offer fun Run(port: int, handle: fun(Request) -> Response) -> s32 uses io, net, time, unsafeListens on port and serves one connection after another, each inside
an arena of its own.
function RunPolled
offer fun RunPolled(port: int, most: int, handle: fun(Request) -> Response) -> s32 uses io, net, time, unsafeThe same server, holding many connections at once.
One loop, one thread, and a poller that says which connections have
something to say (D95). A blocking Serve holds one client no matter
how fast the rest of the server is; this holds as many as the system
will give descriptors for, and the cost per idle connection is one
entry in a kernel table.
most is how many ready descriptors one wait may report. Everything
else waits for the next turn, which is what keeps one noisy client
from starving the rest.
function RunServer
offer fun RunServer(
port: int,
most: int,
handle: fun(Request) -> Response,
limits: Limits) -> s32 uses io, net, time, unsafeThe polled server, with limits of the caller's choosing.
One loop, one thread, and a poller that says which connections have something to say (D95). Each connection has a buffer of its own, so a request that arrives in pieces is put together rather than parsed in halves (D122).
function RunServerOn
offer fun RunServerOn(
listener: s32,
most: int,
handle: fun(Request) -> Response,
limits: Limits) -> s32 uses io, net, time, unsafeThe same loop, on a listener the caller opened.
What a multi-threaded server needs: each thread opens its own listener on the same port and runs this (D135).
struct Before
offer struct BeforeWhat runs before a handler. A response means "answer this and stop".
field run
var run: fun(&mut Request) -> Response?struct After
offer struct AfterWhat runs after a handler, and may change what it said.
field run
var run: fun(&Request, Response) -> Responseclass Layers
offer class LayersThe layers an application runs around every request.
field opening
var opening: List<Before>field closing
var closing: List<After>method Use
fun Use(run: keep fun(&mut Request) -> Response?) uses unsafeAdds a layer that runs before the handler.
method Then
fun Then(run: keep fun(&Request, Response) -> Response) uses unsafeAdds a layer that runs after it.
method Len
fun Len() -> intfunction LayersNew
offer fun LayersNew() -> Layers uses unsafefunction Through
offer fun Through(
layers: &Layers,
request: Request,
handle: fun(Request) -> Response) -> Response uses io, time, unsafeRuns handle with layers around it.
The before layers run in the order they were added, and the first
one that answers wins -- the handler does not run at all. The after
layers run in reverse, so the first layer added is the outermost one,
which is the order every other server does it in and the one that
makes a logger added first see the final answer.
function Timing
offer fun Timing(_request: &mut Request) -> Response? uses time, unsafeA layer pair that writes one line per request.
Timing goes in before and Logged in after; Logger(layers)
installs both, which is what a program actually wants.
function Logged
offer fun Logged(request: &Request, answer: Response) -> Response uses io, time, unsafefunction Logger
offer fun Logger(layers: &mut Layers) uses io, time, unsafeWrites one line per request, with how long it took.
function AllowOrigin
offer fun AllowOrigin(origin: text)What the CORS layer allows. "*" is the default and means anyone.
function AllowMethods
offer fun AllowMethods(methods: text)function AllowHeaders
offer fun AllowHeaders(headers: text)function AllowCredentials
offer fun AllowCredentials(allow: bool)Whether a browser may send cookies. With credentials, "*" is not a legal origin -- the browser rejects the pair -- so a program that turns this on has to name an origin.
function Cors
offer fun Cors(_request: &Request, answer: Response) -> Response uses unsafeAnswers a preflight request itself, and marks every other answer.
function Preflight
offer fun Preflight(request: &mut Request) -> Response? uses unsafeThe other half: OPTIONS is answered without reaching a handler.
function SecurityHeaders
offer fun SecurityHeaders(_request: &Request, answer: Response) -> Response uses unsafeThe headers a browser should be told about every answer.
function RequireToken
offer fun RequireToken(token: text)Requires Authorization: Bearer <token> on every request.
One token for the whole server: a program with users looks them up itself, and this is for the case where a service talks to a service.
function Authorize
offer fun Authorize(request: &mut Request) -> Response? uses unsafefunction RateLimit
offer fun RateLimit(count: int)At most count requests a second, across all clients.
function Limit
offer fun Limit(_request: &mut Request) -> Response? uses time, unsafefunction BodyLimit
offer fun BodyLimit(most: int)function CheckBody
offer fun CheckBody(request: &mut Request) -> Response? uses unsafeclass Poller
offer class PollerWatches descriptors and says which are readable.
field handle
var handle: s32 = -1field ready
var ready: []s32method deinit
deinitmethod IsOpen
fun IsOpen() -> boolmethod Watch
fun Watch(fd: s32) -> bool uses unsafemethod Forget
fun Forget(fd: int) -> bool uses unsafemethod Wait
fun Wait(timeout: int) -> int uses unsafeWaits up to timeout milliseconds and gives back how many
descriptors are ready. At names them.
method At
fun At(index: int) -> intfunction PollerNew
offer fun PollerNew(most: int) -> Poller uses io, unsafeA poller that can report up to most ready descriptors at a time.
function SetNonBlocking
offer fun SetNonBlocking(fd: s32) -> bool uses net, unsafeStops a descriptor from blocking: a read with nothing to read returns instead of waiting, which is what lets one loop serve many.
struct Call
offer struct CallWhat to ask for.
Built up and handed to Call: RequestNew("GET", url) and then the
With... functions, each answering the request so that calls chain.
field method
var method: text = "GET"field url
var url: text = ""field body
var body: text = ""field kind
var kind: text = ""field headers
var headers: [16]Pairfield header_count
var header_count: int = 0field timeout
var timeout: int = 30000How long to wait for the whole answer, in milliseconds. Zero waits as long as the system does.
field redirects
var redirects: int = 5How many redirects to follow. Zero follows none.
field verify
var verify: bool = trueWhether to check the certificate. Off is for a development server with one it signed itself, and says so at the call.
function CallNew
offer fun CallNew(method: text, url: text) -> Callfunction WithHeaderOn
offer fun WithHeaderOn(call: Call, name: text, value: text) -> CallThe same call with one more header.
function WithBody
offer fun WithBody(call: Call, body: text, kind: text) -> CallThe same call with a body and what it is.
function WithBearer
offer fun WithBearer(call: Call, token: text) -> Call uses unsafeAuthorization: Bearer <token>.
function WithBasic
offer fun WithBasic(call: Call, user: text, password: text) -> Call uses unsafeAuthorization: Basic <user:password>, base64 as the scheme wants.
function WithQuery
offer fun WithQuery(call: Call, name: text, value: text) -> Call uses unsafeThe same call with name=value added to the query, escaped.
function WithTimeout
offer fun WithTimeout(call: Call, millis: int) -> CallThe same call, waiting at most millis for the whole answer.
function WithRedirects
offer fun WithRedirects(call: Call, count: int) -> CallThe same call, following at most count redirects.
function WithoutVerification
offer fun WithoutVerification(call: Call) -> CallThe same call, without checking the certificate.
function JsonOf
offer fun JsonOf(value: Value) -> Response uses unsafe200 OK with a JSON value, written here.
function Html
offer fun Html(body: text) -> Response200 OK with an HTML body.
function Text
offer fun Text(body: text) -> Response200 OK with a plain-text body and the character set said out loud.
function Redirect
offer fun Redirect(location: text) -> ResponseA redirect to location.
303 See Other by default, which is the one that turns a POST into a
GET -- the thing a form submission wants and the reason 302 is a
trap.
function RedirectWith
offer fun RedirectWith(status: int, location: text) -> ResponseA redirect with a status of the caller's choosing: 301 for moved for
good, 307 to keep the method.
function Problem
offer fun Problem(status: int, title: text, detail: text) -> Response uses unsafeAn error as a JSON document, the way an API should answer one.
The shape is RFC 7807's: a title, a status and a detail. A client that has to tell a person what went wrong needs more than a status line, and a body that is sometimes text and sometimes JSON is the thing that makes writing a client miserable.
function Escaped
offer fun Escaped(value: text) -> text uses unsafeA string with what JSON cannot carry escaped.
Here rather than in std.json because this is a fragment -- the
value of one member of a document being built by hand -- and the JSON
writer works on whole documents.
function Attachment
offer fun Attachment(name: text, body: text) -> Response uses unsafeA body to be saved rather than shown.
function WithCookie
offer fun WithCookie(answer: Response, name: text, value: text, seconds: int) -> Response uses unsafeThe same response, with a cookie on it.
Path=/ and HttpOnly by default: a cookie a script can read is a
cookie an injected script can read, and a program that wants one says
so with WithHeader itself.
function WithoutCookie
offer fun WithoutCookie(answer: Response, name: text) -> Response uses unsafeThe same response, with the cookie called name taken away.
function WithCache
offer fun WithCache(answer: Response, seconds: int) -> Response uses unsafeThe same response, cacheable for seconds.
function WithoutCache
offer fun WithoutCache(answer: Response) -> Response uses unsafeThe same response, which nothing may cache.
function WithTag
offer fun WithTag(answer: Response, tag: text) -> Response uses unsafeThe same response, with an entity tag so a client may ask again cheaply.
function NotModified
offer fun NotModified(request: &Request, tag: text) -> Response? uses unsafe304 Not Modified when the client already has tag.
A handler calls this first and answers with it when it is not null, which is the whole of conditional GET.
function Unauthorized
offer fun Unauthorized(realm: text) -> Response uses unsafe401 with the scheme a client should use.
function Forbidden
offer fun Forbidden() -> Responsefunction Conflict
offer fun Conflict(why: text) -> Responsefunction Unprocessable
offer fun Unprocessable(why: text) -> Responsefunction TooMany
offer fun TooMany(seconds: int) -> Response uses unsafe429, with how long the client should wait.
function Failed
offer fun Failed() -> Response500, with nothing about what went wrong.
Deliberately: what went wrong goes in the log, where the people who run the server can see it, and not to whoever asked.
function Unavailable
offer fun Unavailable(seconds: int) -> Response uses unsafestruct Route
offer struct RouteOne route: which method, which pattern, and what answers it.
field method
var method: textfield pattern
var pattern: textfield handle
var handle: fun(Request) -> Responseclass Router
offer class RouterA list of routes, tried in order.
field routes
var routes: List<Route>field fallback
var fallback: fun(Request) -> Response = NotFoundHandlerfield has_fallback
var has_fallback: bool = falsemethod Add
fun Add(method: text, pattern: text, handle: keep fun(Request) -> Response) uses unsafeAdds a route. Answers nothing: a router is built once, at the top of a program, so the calls read as a list rather than as a chain.
method Get
fun Get(pattern: text, handle: keep fun(Request) -> Response) uses unsafemethod Post
fun Post(pattern: text, handle: keep fun(Request) -> Response) uses unsafemethod Put
fun Put(pattern: text, handle: keep fun(Request) -> Response) uses unsafemethod Delete
fun Delete(pattern: text, handle: keep fun(Request) -> Response) uses unsafemethod Patch
fun Patch(pattern: text, handle: keep fun(Request) -> Response) uses unsafemethod Head
fun Head(pattern: text, handle: keep fun(Request) -> Response) uses unsafeA route for HEAD. Rarely needed: a GET route answers HEAD by
itself, with the body left off (D122).
method Options
fun Options(pattern: text, handle: keep fun(Request) -> Response) uses unsafemethod Any
fun Any(pattern: text, handle: keep fun(Request) -> Response) uses unsafeOne handler for every method on a pattern.
method Otherwise
fun Otherwise(handle: keep fun(Request) -> Response) uses unsafeWhat answers when nothing else matches. Without one, 404.
method Mount
fun Mount(prefix: text, inner: &Router) uses unsafeAnother router's routes, with prefix in front of each.
Copied rather than nested: a route is a pattern and a function, so mounting is prefixing -- and the match stays one walk over segments instead of a walk per level (D126).
method Allowed
fun Allowed(path: text) -> text uses unsafeThe methods a path has routes for, as GET, POST.
What 405 and OPTIONS both have to say, and the one question a
list of routes cannot answer without walking it twice.
method Len
fun Len() -> intHow many routes there are.
function NotFoundHandler
offer fun NotFoundHandler(_request: Request) -> ResponseWhat a router answers with when it has no route and no fallback.
function RouterNew
offer fun RouterNew() -> Router uses unsafefunction Together
offer fun Together(prefix: text, pattern: text) -> text uses unsafeTwo path pieces with one slash between them.
function Dispatch
offer fun Dispatch(router: &Router, request: Request) -> Response uses io, unsafeFinds the route for request, fills in its path parameters, and
answers with what the handler said.
404 when no pattern matches the path, and 405 when one does but
not for this method -- which is the difference between "no such thing"
and "not like that".
function Matches
offer fun Matches(pattern: text, path: text, into: &mut Request) -> bool uses unsafeWhether pattern matches path, filling params with what :name
stood for.
Segment by segment: :name takes whatever is in that segment, *
takes the rest, and anything else has to be equal.
function ServeRoutes
offer fun ServeRoutes(port: int, most: int, router: Router) -> s32 uses io, net, time, unsafeListens on port and answers with router, polling for readiness.
What a program serving an API calls: the router says what answers what, and this is the loop around it (D112).
function Listen
offer fun Listen(port: int, backlog: int) -> s32 uses net, unsafeOpens a listening socket on port, or a negative number on failure.
function ListenShared
offer fun ListenShared(port: int, backlog: int) -> s32 uses net, unsafeThe same, with the port shared between threads.
SO_REUSEPORT gives each listener its own accept queue on the same
port and lets the system spread connections across them: one listener
per thread is what makes a multi-threaded server scale, and sharing
one listener instead makes every thread wake for every connection
(D135). On a system without it this is one listener, which still
works with one thread.
function Accept
offer fun Accept(listener: s32) -> s32 uses net, unsafeWaits for the next connection.
function Close
offer fun Close(fd: s32) -> s32 uses net, unsafefunction Read
offer unsafe fun Read(fd: s32, buffer: *mut u8, capacity: int) -> int uses netReads into buffer and returns how many bytes arrived, or a negative
number. The buffer is the caller's, which is what makes this allocate
nothing per request.
function WriteAll
offer fun WriteAll(fd: s32, message: text) -> bool uses net, unsafeWrites all of message, which may take more than one call: a socket
is allowed to accept part of what it was given.