HTTP for MoonBit apps that outgrow the built-in client: the module an app starts with, holding a ready client (retries with a budget, deadlines, redirects, cookies, decompression) and a server, on moonbitlang/core/async for native, wasm and js. Typed endpoints and OpenAPI come from gaato/mttp_core, which libraries depend on instead.
moon add gaato/mttp///|
#derive(FromJson)
struct User {
name : String
}
///|
/// Prints a user's name, the HTTP failure, or the network failure.
pub async fn show_user(id : Int32) -> Unit {
let api = @mttp.client(base_url="https://api.example.com")
defer api.close()
let request = @mttp.get("/users/\{id}").response(@mttp.as_json())
let reply = api.send(request) catch {
error => {
println("network: \{error}")
return
}
}
let user : Result[User, _] = reply.body
match user {
Ok(user) => println(user.name)
Err(failure) => println("HTTP \{reply.status}: \{failure}")
}
}///|
fn main {
@mttp.run(async fn() { show_user(1) })
}///|
/// Renames a user with PATCH; true when the server answered 2xx.
pub async fn rename_user(
api : @mttp.Client,
id : Int32,
name : String,
token : String,
) -> Bool {
let request = @mttp.request(@mttp.Request::patch("/users/\{id}"))
.bearer(token)
.body_json({ "name": name })
api.send(request).body is Ok(_)
}| Default | Change it with | |
|---|---|---|
| Retries | Up to two. For GET, PUT, DELETE and other idempotent requests: on 408, 409, 429, 500, 502, 503 and 504 and on network failures. For any request, POST included: when it was never sent. Retry-After is honoured, and a server that asks to wait more than 60 s is not retried. Otherwise the wait starts at 500 ms and doubles, with jitter | retry=@mttp.RetryPolicy::none(), or a policy of your own |
| Retry budget | Retries stay within 20 % of the requests of the last 10 s, plus 10 per second, so a failing server is not flooded | retry_budget=@mttp.RetryBudget::new(..) or @mttp.RetryBudget::unlimited() |
| Deadlines | 30 s for each attempt, 120 s for the whole call, retries and their waits included | timeout_ms=, total_ms=, or .timeout_ms(..) on one request |
| Redirects | Up to 10 hops, never from HTTPS to HTTP. Authorization, Proxy-Authorization and Cookie are dropped when the origin changes, except from http on port 80 to https on port 443 of the same host | redirect=@mttp.RedirectConfig::none(), or .follow_redirects(false) on one request |
| Cookies | None kept | cookies=@mttp.CookieJar::new(@mttp.clock()); the jar belongs to the caller and can be shared between Clients |
| Decompression | gzip, deflate, br and zstd on native and wasm | On native and wasm, a request that sets Accept-Encoding gets its body as sent |
| Body size | Buffered bodies up to 64 MiB after decoding | max_body_bytes=, or .max_body_bytes(..) on one request |
| Proxies | http_proxy, https_proxy, all_proxy and no_proxy from the environment, on native and wasm; http://, https:// and socks5h:// proxies | config= a ClientConfig from gaato/mttp_core/h1client |
| TLS roots | The system's | trust=PemFile("roots.pem") |
| Admission | Every request at once | limiter= a RateLimiter from gaato/mttp_core/client |
| Observation | None | observer= gets one Attempt per attempt; events= gets every ClientEvent: attempts, connection phases, redirects and retries |
| Network and time | The real network, clock and timers | backend=, clock=, timer= (see Tests) |
///|
/// Echoes a request body of up to 64 KiB with its content type; a larger
/// body gets 413.
pub async fn echo(request : @mttp.Request) -> @mttp.Response noraise {
let body = request.body.read_all(max=65536) catch {
TransportError(kind=TooLarge(..), ..) => return @mttp.Response::new(413)
_ => return @mttp.Response::new(400)
}
let content_type = request.headers
.get("content-type")
.unwrap_or("application/octet-stream")
@mttp.Response::new(
200,
headers=@mttp.Headers::of([("content-type", content_type)]),
body=Bytes(body),
)
}
///|
pub async fn serve_echo() -> Unit {
@server.serve(echo, addr="127.0.0.1:8080", on_listen=addr => {
println("listening on \{addr}")
})
}| Package | Targets | What it adds |
|---|---|---|
| gaato/mttp/files | native, wasm | static_files(dir): a directory as a handler, with ETags and 304s; hidden files and paths outside the directory are 404s; ranges=true answers single byte ranges |
| gaato/mttp/codings | native, wasm, js | compress(handler) negotiates zstd, br, gzip or deflate for responses; CompressRequests compresses request bodies; RFC 9842 compression dictionaries for both ends |
| gaato/mttp/ws | native, wasm, js | WebSocket connect and upgrade, with opt-in permessage-deflate on native and wasm |
| gaato/mttp/fetch | js | fetch_handler(handler): the same handler as a fetch export for Cloudflare Workers, Deno, Bun, Node, Fastly, Vercel and AWS Lambda |
| gaato/mttp/runtime | native, wasm, js | VirtualClock for tests, and the clocks and timers behind clock() and timer() |
| gaato/mttp/backend | native, wasm, js | AsyncBackend: the network alone, for a Client built by hand |
| gaato/mttp/trust | native, wasm, js | Trust: which TLS roots a socket connection accepts |
| gaato/mttp/conn | native, wasm | TcpDialer: TCP connections, and TLS over any connection, such as one through a CONNECT tunnel |
import {
"gaato/mttp",
"gaato/mttp/server",
"gaato/mttp_core/endpoint",
"gaato/mttp_core/router",
"gaato/mttp_core/schema",
}///|
/// GET /hello/{name} answers with a greeting.
let hello : @endpoint.ServerEndpoint = @endpoint.endpoint
.get("/hello/{name}")
.input(@endpoint.path("name", @schema.string))
.output(@endpoint.text_out())
.serve_public(name => Ok("hello, \{name}"))
///|
/// The app's endpoints, with the clock and timer a Client's deadlines need
/// when it calls the Router in memory.
fn hello_app() -> @router.Router {
@router.Router::must([hello], clock=@mttp.clock(), timer=@mttp.timer())
}
///|
pub async fn serve_hello(addr : String) -> Unit {
@server.serve(hello_app().handler(), addr~)
}///|
/// Reads a user's name; the Client is a parameter, so a test can pass a stub.
pub async fn user_name(api : @mttp.Client, id : Int32) -> String? {
let user = @mttp.get("/users/\{id}").response(@mttp.as_json_value())
match api.send(user).body {
Ok({ "name": String(name), .. }) => Some(name)
_ => None
}
}
///|
test "user_name reads the name from the reply" {
let stub = @testing.BackendStub::new().when(
request => request.url == "https://api.example/users/1",
@testing.Canned::bytes(200, body=b"{\"name\":\"Ada\"}"),
)
let api = @mttp.client(base_url="https://api.example", backend=stub)
let name : Ref[String?] = Ref(None)
@mttp.run(async fn() { name.val = user_name(api, 1) })
assert_eq(name.val, Some("Ada"))
assert_eq(stub.sent().length(), 1)
}| Need | Module |
|---|---|
| HTTP Digest authentication | gaato/mttp_digest |
| JSON codecs and schemas generated from annotated types | gaato/mttp_schemagen |
| An httpx/requests-style calling surface over mttp | gaato/requesto |
| The compressors behind decompression and codings, for use on their own | gaato/deflate, gaato/brotli, gaato/zstd |
test {
let request = @mttp_core.Request::post("/upload").body_bytes(b"abc")
assert_eq(request.body, Bytes(b"abc"))
assert_eq(request.body.length(), Some(3L))
assert_true(request.body.is_replayable())
}test {
let jar = @cookie.CookieJar::new(@sim.FakeClock::new())
jar.store(
@mttp_core.Headers::of([("Set-Cookie", "sid=1; Path=/; Secure")]),
"https://example.com/login",
)
assert_eq(jar.header_for("https://example.com/"), Some("sid=1"))
assert_eq(jar.header_for("http://example.com/"), None)
}test {
let headers = @mttp_core.Headers::of([("Accept", "text/plain")])
assert_eq(headers.get("ACCEPT"), Some("text/plain"))
}test {
let seen = []
let request = @mttp_core.Request::get("http://example.test/")
let request = {
..request,
attributes: request.attributes.put(@mttp_core.on_phase, event => {
seen.push(event)
}),
}
// A backend looks the callback up and reports what it reached.
if request.attributes.get(@mttp_core.on_phase) is Some(report) {
report(Dialed(addr="example.test:80"))
report(Pooled(reused=false))
}
assert_eq(seen, [Dialed(addr="example.test:80"), Pooled(reused=false)])
}test {
let base = @mttp_core.Url::parse("HTTPS://Example.COM:443/a/b?x=1")
assert_eq(base.to_string(), "https://example.com/a/b?x=1")
let next = base.resolve(@mttp_core.Url::parse("../c d"))
assert_eq(next.to_string(), "https://example.com/c%20d")
}fn as_lines(receive : async (String) -> Unit, max_line_bytes? : Int) -> ResponsePlan[Result[Unit, ResponseFailure], Streaming]fn as_sse(receive : async (SseEvent) -> Unit, max_event_bytes? : Int, stop? : (SseEvent) -> Bool) -> ResponsePlan[Result[Unit, ResponseFailure], Streaming]let claude = @anthropic.Anthropic::new(
api_key~,
@mttp.backend(),
@mttp.clock(),
timer=@mttp.timer(),
)fn client(base_url? : String, headers? : Headers, timeout_ms? : Int, total_ms? : Int, max_body_bytes? : Int, retry? : RetryPolicy, retry_budget? : RetryBudget, redirect? : RedirectConfig, limiter? : &RateLimiter, trust? : Trust, config? : ClientConfig, cookies? : CookieJar, backend? : &Backend, clock? : &Clock, timer? : &Timer, observer? : (Attempt) -> Unit, events? : (ClientEvent) -> Unit, random? : () -> Double) -> Clientlet jar = @mttp.CookieJar::new(@mttp.clock())
let site = @mttp.client(cookies=jar)test {
let response = @mttp_core.Response::new(200)
let response = {
..response,
attributes: response.attributes.put(@mttp_core.close_on_shutdown, true),
}
assert_eq(response.attributes.get(@mttp_core.close_on_shutdown), Some(true))
}fn run(main : async () -> Unit) -> Unitfn main {
@mttp.run(async fn() { ... })
}Install
Download zipHTTP for MoonBit apps that outgrow the built-in client: the module an app starts with, holding a ready client (retries with a budget, deadlines, redirects, cookies, decompression) and a server, on moonbitlang/core/async for native, wasm and js. Typed endpoints and OpenAPI come from gaato/mttp_core, which libraries depend on instead.