http — HTTP client and server
include httpWARNING
Not available in bot scripts. There, requests go through bot.http({method, url, headers, body, timeout}) → {ok, status, body, error}: at most 3 per run, up to 5 s each; it does not raise, so check r["ok"].
| Function | What it does |
|---|---|
http.get(url, opts) | GET → {status, body, headers} |
http.post(url, body, opts) | POST; a string is sent as is, anything else as JSON |
http.request(method, url, opts) | any method; opts: body, headers, timeout |
http.serve(addr, routes, ready) | runs a server; returns after http.stop() |
http.stop() | stops the server (from a handler) |
http.json(body, status = 200, headers = {}) | a JSON response |
http.text(body, status = 200, headers = {}) | a text response |
Client
The response is a dict: status (int), body (a string), headers (lower-case names). A 404 or 500 status is not an error but a value.
include http
include json
r = http.get("https://api.example.com/orders?page=2", {headers: {"Authorization": "Bearer token"}, timeout: 5})
if r["status"] == 200 {
orders = json.parse(r["body"])
println(orders.len)
} else {
println("error ${r["status"]}")
}include http
http.post("https://api.example.com/orders", {sku: "A1", qty: 2})
http.post("https://api.example.com/log", "just text")
http.request("DELETE", "https://api.example.com/orders/7", {timeout: 3})An error is only a connection failure or a timeout (opts.timeout, 10 s by default): an http error, caught by try.
include http
r = try http.get("http://localhost:9/x", {timeout: 2}) else (e) -> nilA network script in the terminal needs a longer overall timeout: mzs -t 30s fetch.mzs. try does not catch running out of it.
include http
http.get("example.com")url must start with http:// or https://Server
A route key is "METHOD /path/{param}". The handler gets a request dict: method, path, params, query, headers, body (a string), host, remote.
include http
include json
ITEMS = [{id: 1, name: "haircut"}, {id: 2, name: "shave"}]
http.serve(":8080", {
"GET /health": { (_) -> "ok" },
"GET /item/{id}": { (req) ->
item = ITEMS.find { it["id"] == req["params"]["id"].int }
item ?? http.json({error: "not found"}, 404)
},
"POST /order": { (req) ->
order = json.parse(req["body"])
http.json({ok: true, qty: order["qty"]}, 201)
},
"GET /shutdown": { (_) -> http.stop(); "bye" },
}, { (url) -> println("listening on ${url}") })mzs -t 1h server.mzs
curl localhost:8080/item/2| The handler returned | Response |
|---|---|
nil | 204, no body |
| a string | 200, text/plain |
a dict with status | that status, body, headers |
| any other value | 200, JSON |
include http
http.json({a: 1}, 201) # → {"status":201,"body":"{\"a\":1}","headers":{"content-type":"application/json; charset=utf-8"}}
http.text("no", 418) # → {"status":418,"body":"no","headers":{"content-type":"text/plain; charset=utf-8"}}- Requests are handled one at a time.
- Each request gets a fresh step and time limit; a failed handler gives 500 and the server keeps running.
- A wrong path is 404, a wrong method 405.
Server and client in one script
":0" picks a free port; ready gets the address once the server is up.
include http
async fn client(base) {
a = http.get(base + "/item/2")
b = http.get(base + "/item/9")
http.get(base + "/stop")
[a["status"], b["status"], b["body"]]
}
t = nil
http.serve(":0", {
"GET /item/{id}": { (req) ->
if req["params"]["id"] == "2" { {id: 2} } else { http.json({error: "no"}, 404) }
},
"GET /stop": { (_) -> http.stop(); "bye" },
}, { (url) -> t = client(url) })
t.await # → [200,404,"{\"error\":\"no\"}"]