Web requests: http
http asks a web server for something: a page, data from an API, a form sent. It is built in; no import is needed.
res: http.response = http("http://localhost:8080/health").get()
print(res.status)
print(res.body)http(url) makes a request, and get() (or post(), put(), patch(), delete(), head()) sends it and gives the response. head() asks for the status and headers only: the body stays empty. The URL starts with http://, or https:// for an encrypted connection.
Building a request
A request can be given more before it is sent:
req: http = http("http://api.local/users")
req.header("Authorization", "Bearer abc123")
req.query("search", "Ann Smith") // ?search=Ann%20Smith
req.timeout(10) // seconds; 30 if not given
res: http.response = req.get()| Method | Does |
|---|---|
req.header(name, value) | adds a header; call it again for more |
req.query(name, value) | adds name=value to the URL’s query, encoded |
req.cookie(name, value) | sends a cookie (all of them in one Cookie header); the value is encoded where it has to be |
req.timeout(seconds) | how long to wait for the server, each time (a float; 10 works too) |
req.redirects(n) | how many redirects to follow, 10 if not given; 0 gives the redirect itself |
req.trust(file), req.pin(key), req.insecure() | for https: what to trust (see https) |
host, User-Agent: luma and the body’s Content-Type and Content-Length are added by themselves (a header you give yourself counts instead).
Sending data
| Method | Sends |
|---|---|
req.json(value) | a json value as JSON text, with Content-Type: application/json |
req.field(name, value) | a form field; call it again for more (application/x-www-form-urlencoded) |
req.body(text) | a str as it is; give its Content-Type with header |
req: http = http("http://api.local/users")
req.json({"name": "Alice", "age": 30, "tags": ["admin"]})
res: http.response = req.post()
login: http = http("http://intranet.local/login")
login.field("user", "alice")
login.field("password", "s3cret")
answer: http.response = login.post()A json literal can mix types, so it is the way to send an object of any shape.
The response
| Field or method | Holds |
|---|---|
res.status | the status code: 200, 404, … |
res.body | the body, a str |
res.headers | the headers, a {str: str} with the names in lower case: res.headers["content-type"] |
res.cookies | the cookies the server set, by name: res.cookies["session"] (their values, without Path, Expires and the rest) |
res.version | the HTTP it came over: "1.1", or "2" for HTTP/2 |
res.json() | the body read as JSON |
res: http.response = http("http://api.local/users/1").get()
if res.status == 200 {
user: json = res.json()
name: str = convert(user["name"])
print(name)
} else if res.status == 404 {
print("no such user")
}A status like 404 or 500 is the server’s answer, not an error: check res.status. A header sent twice holds both values, separated by , (Set-Cookie lines by line breaks, as a cookie’s date has commas). Use has(res.headers, "location") to see whether a header is there.
https
https:// URLs are encrypted with TLS 1.3, so that nobody between the program and the server can read or change what they send. The server’s certificate is checked the way browsers do, so you know who answers:
res: http.response = http("https://api.github.com/zen").get()- it is signed, through the authorities the server sends, by an authority this computer trusts;
- it is for the host in the URL (
*.example.comcovers one level:www.example.com, nota.b.example.com); - it hasn’t expired, and is meant for a server;
- the server holds its key: it signs the handshake with it.
A server on this computer or a private network often has a self-signed certificate, which no authority vouches for. Luma accepts it there, on its own:
localhost, and names without a dot (db,nas: Docker services, computers on the LAN)- names that end in
.local,.localhost,.internal,.lanor.home.arpa - addresses
127.*,10.*,172.16.*to172.31.*,192.168.*and169.254.*
It goes by the name in the URL, never by the address a name stands for, since that could be faked.
Your own certificates: trust and pin
For a self-signed certificate on a public name, or your own authority, tell the request what to trust:
req: http = http("https://my-vps.example.org/status")
req.trust("certs/server.pem")
res: http.response = req.get()| Method | Trusts |
|---|---|
req.trust(file) | the certificates in a PEM file (-----BEGIN CERTIFICATE-----), besides this computer’s authorities. An authority in it vouches for the certificates it signs (checked like any other); the server’s own certificate in it is accepted as it is, whatever names it has |
req.pin(key) | only a server with exactly this key: sha256// and the base64 of the SHA-256 of its public key (as curl’s --pinnedpubkey writes it). It keeps working when the certificate is renewed with the same key |
req.insecure() | anything: the connection is encrypted, but anyone on the way could pretend to be the server. Only for networks you trust |
You don’t need to work out a pin yourself: pin anything, and the error says the right one.
error 14: the key of my-vps.example.org is sha256//r8udi/Mxd6pLO7y7hkWUYWjm96mA2t1XMk5Ylzhfyg=, not the pinned sha256//AAAA...trust and pin make a local name checked too.
The authorities this computer trusts
On Linux they are the system’s bundle: /etc/ssl/certs/ca-certificates.crt (Debian, Ubuntu), /etc/pki/tls/certs/ca-bundle.crt (Fedora, RHEL), /etc/ssl/cert.pem (Alpine), … read once, when the first certificate is checked. The environment variable SSL_CERT_FILE names another PEM file instead, as for curl and many other programs. On Windows they are the authorities in Windows’ certificate store (the “Trusted Root Certification Authorities” that certmgr shows). Windows keeps only some of its authorities on the disk, and fetches the others the first time a certificate needs one: when a site’s authority isn’t in the store, Luma asks Windows to build the site’s chain, which fetches it, and then checks the chain with it, as it checks any other. With SSL_CERT_FILE, only that file counts.
Event streams
Some servers answer with a stream of events that keeps coming: live updates, or the text of an AI model as it is written. events() sends the request and reads them one at a time:
req: http = http("https://api.example.com/v1/stream")
req.header("Authorization", "Bearer abc123")
req.json({"prompt": "Hello"})
feed: http.feed = req.events("POST")
if feed.status != 200 {
print("failed: ${feed.status} ${feed.body}")
}
while true {
e: ?http.event = feed.next()
if e == nil {
stop
}
print(e.data)
}req.events()sends aGET;req.events("POST")(or another method) sends the request’s body too. It gives anhttp.feedonce the status and headers have come:feed.statusandfeed.headers.feed.next()waits for the next event and gives anhttp.event, ornilwhen the stream has ended. An event hasdata(itsdata:lines, joined with\n),kind(itsevent:,"message"if it has none) andid.- An answer that isn’t a stream (a status other than 200, or another
Content-Type) is read whole intofeed.body, andnext()givesnil: so an API’s error message can be shown. - Between events
next()waits as long as it takes, unlessreq.timeout(...)was set: then that long at most, and error 14 after it. feed.close()stops reading before the end. Comments (:lines) andretry:are skipped, and the stream can come in chunks.- It doesn’t reconnect by itself: to go on after a dropped connection, send the request again, with the last
idin aLast-Event-IDheader.
To send events from a Luma server, see Server-sent events.
WebSockets
req.socket() connects to a WebSocket: the URL starts with ws://, or wss:// for an encrypted one. Headers given with header, and trust, pin and timeout, go with it:
req: http = http("wss://example.com/feed")
req.header("Authorization", "Bearer abc123")
ws: http.socket = req.socket()
ws.send("{\"subscribe\": \"prices\"}")
while true {
msg: ?str = ws.read()
if msg == nil {
stop
}
print(msg)
}ws is an http.socket, the same as a server’s: read, send, close, open, timeout and the rest are in WebSockets. If the server doesn’t take it, error 14 tells what it answered: example.com answered 401 instead of a WebSocket: ....
HTTP/2
Requests to https:// servers that speak HTTP/2 use it by themselves: Luma offers it when connecting, and the server chooses. Nothing in the program changes; res.version tells which it was.
res: http.response = http("https://example.com/").get()
print(res.version) // 2- One connection per server, shared: requests at the same time (from
waitorspawn, or handlers of a server) go over it side by side, as separate streams, instead of each waiting for a connection. - The same as HTTP/1.1 for everything else: headers, bodies of any size, redirects,
timeout(how long to wait each time something is expected),trust,pin, event streams, errors. - A connection the server closed meanwhile is noticed, and the request goes again on a new one, as with HTTP/1.1.
http://stays HTTP/1.1, and so do WebSockets (wss://), which most servers serve only that way.
Redirects
A response that sends you elsewhere (301, 302, 303, 307, 308) is followed: you get the response of where it leads. After a 303, and after a 301 or 302 to a post(), the next request is a get() without the body, as browsers do. More than 10 redirects in a row (or than redirects(n)) is an error.
Errors
What keeps a request from getting an answer raises error 14, which try catches:
err: error = nil
try err {
res: http.response = http("http://localhost:8080/").get()
print(res.status)
}
if err != nil {
print(err.message)
}| Message | When |
|---|---|
cannot connect to localhost:8080: connection refused | nothing answers there (see Network connections for the others) |
timed out reading from api.local | longer than the timeout |
invalid URL "x": it must start with http://, https://, ws:// or wss:// | the URL isn’t one |
the certificate of api.example.com isn't for that name (it is for example.org) | the certificate is for another name |
the certificate of api.example.com expired on 2024-05-01 | an old certificate |
the certificate of api.example.com isn't signed by an authority this computer trusts (...) | self-signed, or an authority this computer doesn’t know: see trust and pin |
the key of api.example.com is sha256//..., not the pinned sha256//... | another key than the pinned one |
the TLS handshake with api.local:443 failed: ... | the server and Luma can’t agree on encryption (see Secure connections) |
too many redirects (more than 10) from http://... | redirects that don’t end |
invalid HTTP response from api.local: ... | the server’s answer isn’t HTTP |
The error is reported at the line of your program that sent the request.
Details
- Over HTTP/1.1, connections are kept for the next request to the same server (keep-alive): up to 4 for each, each for 30 seconds. A server that closed a kept connection meanwhile is noticed when nothing of its answer comes, and the request is sent again on a new connection. A connection is closed when the server says
Connection: close, or its answer has no length (it ends when the connection does).insecure(),trustandpincount: a connection made with other checks of the certificate isn’t used. The answer can have aContent-Length, come in chunks, or last until the server closes. - Compressed answers: Luma asks for gzip (
Accept-Encoding: gzip, deflate) and givesres.bodydecompressed, with the headers saying so (nocontent-encoding, the newcontent-length). A request with its ownAccept-Encodingheader gets the body as it came. Event streams ask for none. - WebSockets offer
permessage-deflate: see WebSockets. print(res)shows the whole response, andprint(req)the request.httpandhttp.responseare built-in type names:httpcan’t be a variable’s name.- HTTP/2 is RFC 9113 with HPACK: the headers Luma sends are plain (no compression of its own), and those it gets can be compressed every way the standard has. A reset stream raises error 14 with its code:
example.com reset the request: INTERNAL_ERROR (2). - It is written in Luma, on top of
tcpandbuffer, and comes with the compiler;httpsusessock.secure.
Not available yet
- TLS 1.2 (nearly every server has TLS 1.3), and checking whether a certificate was revoked.
- A cookie jar that keeps cookies between requests by itself: take them from
res.cookiesand give them withreq.cookie. Compressing request bodies (do it yourself:body.gzip()and aContent-Encoding: gzipheader). - Servers: see Web servers.