module std.http
std.http — HTTP client (HTTP/1.1, HTTP/2), server, router, SSE and WebSocket (II.1 std.http, [С ч. II], D-3920..D-3971). Every client
request has the effect net.
use std.http { Client as Http, HttpConfig }
let r = Http.get("http://example.org/ping")?
if r.ok() { print(r.text()!) }
let p = Http.postText("https://api.example.org/items", "{\"n\":1}", [Header{ name: "Content-Type", value: "application/json" }],
HttpConfig{ timeout: 5s })?- Requests are made through the static functions of
Client(Http.get(url)); the connection pool is process-wide, so tasks share keep-alive connections without sharing a value. A status of 4xx/5xx is a normalResponse, not an error. - Errors are
NetErrorvalues like in std.net (§6.5, D-2203):Timeout(the whole request, including redirects, did not finish withinHttpConfig.timeout),Unavailable(refused, reset, unreachable, name not found),AccessDenied,Cancelled, andProtocolErrorfor everything else; itsmsgstarts withhttp:(bad URL or header, malformed response, body abovemaxBody, too many redirects) ortls. - Waits park only the calling task and are cancellation points; a cancelled task (or one whose chain deadline passed) leaves the request at once and its connection is closed.
- HTTP/1.1 for
http://;https://offers HTTP/2 in ALPN and uses it when the server selects it (D-3997;HttpConfig.http2). HTTP/1.1:Content-Length,chunked(response bodies always, request bodies withHttpConfig.chunkedUpload) and close-delimited bodies; keep-alive with a pool (8 idle connections per origin, 30 s); a pooled connection that turns out dead is replaced transparently for idempotent methods; redirects (301/302/303/307/308,maxRedirects, default 5; credentials are not sent to another origin; https to http is refused).https://verifies the certificate against the system roots orca. - Response bodies are read completely (
maxBody, default 64 MiB;Client.openStreamreads them piece by piece, D-3970); compressed content is not requested or decoded. Intrinsics: runtime/src/http1/http1.cpp.
Example:
use std.http { Server, ServerConfig, Router, Request, Reply, Client }
fn run() -> () | NetError | DecodeError | Panicked net, io, time {
let srv = Server.bind(ServerConfig{ port: 0, followNode: false })?
defer srv.close()
let stop = srv.handle()
let router = Router.new().get("/hello/:name", (req: Request) => Reply.text("hi {req.param("name") ?? "?"}"))
let base = "http://127.0.0.1:{srv.port()}"
scope {
spawn stop.serve(router)
let r = Client.get("{base}/hello/Ann")?
print("{r.status} {r.text()?}")
stop.shutdown()
()
}?
}
fn main() io, net, time {
match run() {
NetError _ => print("net error")
DecodeError _ => print("decode error")
Panicked _ => print("panicked")
_ => {}
}
}Вывод
200 hi Ann
Типы
data BodyReader | A body read piece by piece |
data BodyWriter | Writer of a streamed response body (Reply.stream). |
data Client | The namespace of the client functions |
data Header | One header field. |
data Http2 | An HTTP/2 connection to one origin (RFC 9113). |
data Http2Handle | A copyable reference to an Http2 connection for other tasks (Http2.handle()) |
data HttpConfig | Settings of a request. |
type Middleware | Wraps a request |
type Next | The rest of the chain as seen by a middleware |
data Reply | The answer of a handler. |
data Request | A request received by a Server. |
data Response | An HTTP response. |
data ResponseStream | A response whose head has arrived and whose body is read piece by piece (D-3970) |
data Router | Routes by method and path pattern. |
data Server | An HTTP/1.1 server (II.1 std.http) |
data ServerConfig | Settings of a Server. |
data ServerHandle | A copyable token that can stop a server from a handler or another task (Server.handle()). |
data SseConfig | Settings of SseStream.open. |
data SseEvent | One event received from an event stream. |
data SseStream | The reading side of a server-sent events connection (text/event-stream). |
data SseWriter | Writer of a server-sent events stream (Reply.sse). |
data WebSocket | An open WebSocket (RFC 6455), made by WebSocket.connect (client) or handed to the function of Reply.websocket (server). |
data WsConfig | Settings of WebSocket.connect. |
enum WsKind | Kind of a WebSocket message. |
data WsMessage | A message received on a WebSocket. |
Функции
chunks | The body of a request as a stream of pieces |
logRequests | Logs METHOD path -> status (N ms) on stderr for every request. |
requireHeader | Answers status (default 401) without calling the handler unless the request has header name (equal to value, when value is not empty) |
timing | Adds Server-Timing |
withMiddleware | handler wrapped in mw |