The platform · HTTP
Other servers, bodies as they came, and cookies
The server answers HTTP, and asks too: an API's JSON, a sign-in provider's token, a linked page. This page covers requests to other servers, request bodies, raw and forwarded answers, and cookies.
Every sample here is from server/test/app/Samples.roc, compiled and run by the server platform's tests.
Asking another server#
## Tomorrow's forecast for a city, from a JSON API another server answers, with a token from the
## environment: what it says, or why it says nothing.
forecast! : Str, Str => Try({ tomorrow : Str }, [HttpErr(Str), TimedOut, TooLarge, InvalidJson(Str), Refused(U16)])
forecast! = |api, city| {
token = Env.var!("FORECAST_TOKEN") ?? "none"
res = Http.fetch!("${api}/forecast", { query: [("city", city)], headers: [("authorization", "Bearer ${token}")] })?
if (res.ok) Ok(res.json()?) else Err(Refused(res.status))
}
## An order sent to a shop's API as JSON, with a token, then cancelled with the same token: the
## order's id, which the shop's answer gave.
order! : Str, Str, { item : Str, count : U64 } => Try(Str, [HttpErr(Str), TimedOut, TooLarge, InvalidJson(Str), Refused(U16)])
order! = |shop, token, order| {
authed : Http.Init
authed = { headers: [("authorization", "Bearer ${token}")] }
placed : { id : Str }
placed = Http.fetch!("${shop}/orders", { ..authed, method: Post, body: Http.json(order) })?.json()?
res = Http.fetch!("${shop}/orders/${placed.id}", { ..authed, method: Delete })?
if (res.ok) Ok(placed.id) else Err(Refused(res.status))
}Http.fetch!(url, init) works like JavaScript's fetch: it sends a request and waits for the whole answer, holding no thread meanwhile (how calls pause). init is an Http.Init record. Every field has a default, so {} is a plain GET:
method:Get,Post,Put,Patch,Delete,Head,Options, orOther("PROPFIND")for any other, sent as written.headers:(name, value)pairs, sent as given.query: pairs, percent-encoded and added to the URL's query (after an&if it has one).body:Empty(the default), orHttp.json(value),Http.form(pairs),Http.plain_text(text)orHttp.bytes(list). Each setscontent-typeunlessheadershas one; bytes set none, likefetchwith aUint8Array.timeout_ms,max_bytesandredirect: the limits, below.proxy:FromEnv,DirectorVia(url), below.
A record literal works wherever an Http.Init is expected. To keep one and build on it, annotate it (as authed above) and update it: { ..authed, method: Delete }.
Any status is an answer: Ok holds an HttpResponse with res.status, res.ok (true for a 2xx), res.headers, res.header(name) (any case), res.text(), res.json() (decoded as the type you ask for, or InvalidJson(why)) and res.bytes(). Err means no answer at all.
An older API (Http.get, post_form, post_json, with_header, send!(request, opts), send_request!, Http.header, Http.text) is deprecated; each is fetch! underneath. The storage package's S3 client is still given Http.send!: it is plain Roc on no platform, so it can't name Http.Init.
Limits and errors#
## A page someone else names (a link's preview): 5 s at most, 64 KiB at most, and a redirect is
## the answer, not followed.
preview! : Str => Try(HttpResponse, [HttpErr(Str), TimedOut, TooLarge])
preview! = |url| Http.fetch!(url, { timeout_ms: 5_000, max_bytes: 65_536, redirect: Manual })By default a request may take 30 seconds (timeout_ms), its body up to 64 MiB (max_bytes), and redirects are followed (redirect: Follow). For a URL a stranger gave you, ask for less, as above. 0 means no limit; Manual returns a redirect as the answer. The errors:
HttpErr(why): no answer. The address was unreachable, the connection or TLS failed, the server broke HTTP, or a header had a line break.TimedOut: no whole answer in time, counted from connecting to the body's last byte.TooLarge: the body was over the limit, by itscontent-lengthor as it arrived.
Redirects are followed like a browser's fetch, 20 at most. A 303 (or a 301 or 302 answering a POST) becomes a GET without its body; authorization and cookie headers aren't sent to another origin. TLS is rustls, checked against the web's certificate authorities. Nothing is decompressed: if you send accept-encoding, you get the body as the server sent it.
Connections and proxies#
## A partner's API, through the proxy its network asks for (`PARTNER_PROXY`), when one is set; the
## app's other requests go as `HTTPS_PROXY`, `HTTP_PROXY` and `NO_PROXY` say.
partner! : Str => Try(HttpResponse, [HttpErr(Str), TimedOut, TooLarge])
partner! = |url|
match Env.var!("PARTNER_PROXY") {
Ok(proxy) => Http.fetch!(url, { proxy: Via(proxy) })
Err(NotFound) => Http.fetch!(url, {})
}Connections are kept alive and reused by the next request to the same place (scheme, host, port and proxy), so an API you call often costs one TCP and TLS handshake, not one per request. An idle connection is kept 30 seconds, or a second less than its server says (keep-alive: timeout=5); at most 32 idle per place, any number open. If the server closed a kept connection meanwhile, the request is retried once on a new one, if it was never sent or is safe to send twice (GET, HEAD, OPTIONS, TRACE, PUT, DELETE, or with an idempotency-key header), as Go's client does.
- The environment's proxy (
FromEnv, the default), read as Go reads it:HTTPS_PROXYforhttpsURLs,HTTP_PROXYforhttp. Never forlocalhost, a loopback address, or a hostNO_PROXYnames.NO_PROXYtakes*, an address, a range (10.0.0.0/8),example.com(that name and every name under it) or.example.com(only names under it), each with an optional:port. - A request's own proxy:
Directuses none;Via(url)uses that proxy for every host. A proxy URL ishttp://orhttps://; a user and password in it go asproxy-authorization. An unreadable proxy URL is anHttpErr, never a silent way around the proxy. - Through the proxy, an
httprequest goes to the proxy whole. Anhttpsone goes through aCONNECTtunnel with TLS to the server inside, so the proxy sees none of it.
Reading an answer as it arrives#
## The lines of an answer too large to hold (an export, a log), counted as its chunks come, none
## kept after it is counted; an answer that isn't a success stops at its head.
lines! : Str => Try(U64, [HttpErr(Str), TimedOut, TooLarge, Stopped([Refused(U16)])])
lines! = |url|
Http.fetch_chunks!(
url,
{ timeout_ms: 0, max_bytes: 0 },
0,
|count, received|
match received {
Head(res) => if (res.ok) Ok(count) else Err(Refused(res.status))
Chunk(bytes) => Ok(count + bytes.count_if(|byte| byte == '\n'))
},
)Http.fetch_chunks!(url, init, start, step!) makes the same request as fetch! but never holds the whole answer. It calls step! with Head(res) first (status and headers, empty body), then Chunk(bytes) for each part of the body as it arrives. Like a fold, each call gets the previous return value, starting from start; the value after the last chunk is the result. If step! returns an Err, the request stops and its connection closes (Err(Stopped(why))).
Use it for a body too large to hold, or one to pass on as it comes, like a language model's answer sent word by word to a stream of events. timeout_ms runs to the last byte and max_bytes counts every chunk, so set both to 0 for a long stream.
Request bodies are bytes#
## An upload's digest: its body, the bytes as they came.
upload_digest : Server.Request -> Server.Response
upload_digest = |request| Server.response(200, [{ name: "content-type", value: "text/plain" }], Sha256.hex(request.body))A request's body is a List(U8), never decoded on the way: an upload is exactly what the client sent. Server.text_of(request) reads it as UTF-8 (U+FFFD where invalid). Server.bytes(status, headers, bytes) answers with raw bytes.
An endpoint decodes its input from the body only when it is JSON (application/json, or a type ending in +json) or a form (URL-encoded, or multipart/form-data, whose files come as their names). For any other type (an image, a video), give the handler the input type {} and read request.body yourself; a handler that expects fields answers such a body 415. A multipart form's files are Server.files(request), or one by field with Server.file(request, field), each with its name, type and bytes.
A route file may name the rules its body is checked with (post_body = Signup.form, from packages/forms). Form fields and a JSON object are then read alike, and what the rules refuse never reaches the handler: it gets 422, with the issues as JSON (endpoints).
A request's body is read whole before your code runs, 16 MiB at most unless the server's --max-body (MAX_BODY) allows more (running it).
Passing on a body from elsewhere#
## A file from another server (a CDN), sent on as it comes, its range and cache questions with it.
from_cdn : Server.Request, Str -> Server.Response
from_cdn = |request, url| {
upstream = { method: "GET", url, headers: Server.passed_on(request) }
Server.forward(upstream, [{ name: "cache-control", value: "public, max-age=86400" }])
}Server.forward(upstream, headers) is an answer whose body never passes through Roc. The host asks upstream and streams the answer on, so a 500 MB video costs your code nothing and starts playing at once. The answer takes upstream's status (200, 206 for a range, 304, 404) and its body's headers (content-type, content-length, content-range, accept-ranges, etag, last-modified); headers you give are added or replace those.
- Only what your code says goes upstream. The host adds nothing from the request, so its cookies stay here.
Server.passed_on(request)gives the request'sRange,If-Range,If-None-MatchandIf-Modified-Sinceheaders to pass on. Change the request record first (drop a range that doesn't fit, say) to change what is asked. - An error upstream (400 or more) is answered with its status and standard reason as text, never upstream's body, which might name a bucket. No answer is a 502 (a 504 after 30 s), logged without the URL's query, where a presigned URL keeps its signature. A body cut short closes the client's connection, so it never passes as complete.
- The storage package's
Storage.serve!is a forward to S3 for an S3 bucket (storage); for a directory or memory, the server sends the file it keeps (Server.stored).
Cookies#
## A session for a month, over HTTPS only, for this host alone (`__Host-`).
signed_in : Server.Response, Str -> Server.Response
signed_in = |answer, token| Server.set_cookie(answer, "__Host-session", token, { ..Server.cookie_defaults, secure: Bool.True, max_age_s: 30 * 86_400 })
## A link's review cookie, until the link runs out (ms), for the review pages only.
reviewing : Server.Response, Str, U64 -> Server.Response
reviewing = |answer, token, until| Server.set_cookie(answer, "review", token, { ..Server.cookie_defaults, expires_ms: until, path: "/review", same_site: Strict })
## The session gone: cleared with the attributes it was set with.
signed_out : Server.Response -> Server.Response
signed_out = |answer| Server.clear_cookie(answer, "__Host-session", { ..Server.cookie_defaults, secure: Bool.True })Server.set_cookie(answer, name, value, options) adds a Set-Cookie header. Server.CookieOpts holds its attributes. Server.cookie_defaults, changed with a record update, are: path /, http_only, same_site: Lax, this host only, until the browser closes. When the app's public URL is HTTPS, the server marks every cookie it sets Secure, so leaving secure off only matters over plain HTTP in development.
max_age_s(Max-Age) andexpires_ms(Expires, in milliseconds since the epoch) are left out when 0. With neither, the cookie ends when the browser closes.secure,http_only,same_site(Lax,StrictorNone),pathanddomainare each left out when empty. Browsers drop a__Host-cookie unless it issecurewith path/and no domain, and dropSameSite=Nonewithoutsecure.Server.clear_cookietakes the path, domain andsecurethe cookie was set with.Server.with_cookieandServer.without_cookieset and clear one with the defaults. The value is%XX-encoded;Server.cookie(request, name)decodes it.
.well-known, and every method#
.well-known/oauth-authorization-server/+server.roc # GET /.well-known/oauth-authorization-server
uploads/[name]/+server.roc # put!: an upload, its body the bytes
mcp/+server.roc # respond!: every method, as it likesA .well-known directory is routed like any other, so what other servers look for there (an OAuth server's metadata, security.txt) is an ordinary route file. Other directories starting with a dot aren't routed.
A +server.roc usually defines one function per method (get!, post!, put!…). respond! answers every method the file doesn't name: given the request, the path's params and the context, it returns its own Server.Response. Use it for a protocol that speaks POST and GET at one URL, or a page a package draws (the jobs page). It isn't an endpoint, so it stays out of /openapi.json (endpoints).
## Every method, as it comes.
respond! : { request : Server.Request, params : {}, context : c } => Server.Response
respond! = |{ request, .. }| Server.response(200, [{ name: "content-type", value: "text/plain" }], "${request.method} ${Server.text_of(request)}")One method can answer as it likes too, and stay an endpoint: a handler whose answer is Try(Server.Response, Endpoint.Refusal) has its Ok sent as it is (a text, a file, a redirect that sets a cookie), and its refusals as any handler's.
Not yet#
- HTTP/1.1 only, each way: no HTTP/2, and no SOCKS proxy.
- A request's body is whole in Roc, in or out: no streaming. (Another server's answer can be read in chunks, and a forwarded body never enters Roc.)