std.http
HTTP/1.1, the server and the client, over the connections of std.net, with TLS for https.
The server gives every request to one function, the handler, which reads the Request and fills the Response: serve runs it for each request, each connection on a task of its own, so the handler runs on several threads at once. A request can also become a WebSocket.
http.serve("0.0.0.0", 8080, [](ref http.Request req, ref http.Response res) {
if (req.matches("GET /hello/{name}")) {
res.write("Hello, " + req.param("name") + "!")
} else {
res.status = 404
}
})The client sends a request and gives back the whole response: get, post and send open a connection for each request, while a Client keeps them open for the next requests to the same host. It follows the redirects, asks for gzip and decompresses. A status of error, as 404, is a response like the others; an exception of type Error is a failure of the network, a timeout, or an answer that is not HTTP.
http.Response res = http.get("https://example.com/")
println("{} {}", res.status, res.headers.get("content-type"))The guide: Networking and HTTP, and a whole service in Final project: a web service.
Generata dalla documentazione nei sorgenti della libreria, che è in inglese.
#Tipi
#Header
struct HeaderA header of a request or of a response.
string name: "Content-Type", in the case it was written instring value: "text/html"; one received has no spaces around it
#Headers
struct HeadersThe headers of a request or of a response, in their order. The names are compared without case, as HTTP wants: get("content-type") finds "Content-Type". A name can have several headers, as Set-Cookie.
res.headers.set("Cache-Control", "no-store")
string agent = req.headers.get("user-agent") // "" without itlist<Header> items: in their order, also those with the same name
#Headers.get
string get(string name) constA copy of the value of the first header with the name, "" without one.
#Headers.has
bool has(string name) constWhether there is a header with the name, also with an empty value.
#Headers.set
void set(string name, string text)Replaces the headers with the name with one, at the end, with a copy of text. An exception as for add, after the old ones are removed.
#Headers.add
void add(string name, string text)Adds a header at the end, with a copy of the name and of text, also when there is one with the same name. An exception for an empty name, a name with a space, a control character or :, and a value with a new line, which would start another header.
#Headers.remove
void remove(string name)Removes all the headers with the name; none is not an error.
#Request
struct RequestA request of HTTP: on the server, the one that the handler receives, already read whole; on the client, the one that send sends, made with Request(method, url).
The handler of a server chooses the route with matches, and reads the parameters of the route with param, those of the query with queryValue, the headers and the body:
if (req.matches("GET /users/{id}")) {
i64 id = i64(req.param("id")) // an exception, so a 500, if it is not a number
string page = req.queryValue("page")
} else if (req.matches("POST /users")) {
User user = json.decode<User>(req.text())
}A client writes its headers and its body before sending it:
http.Request req = http.Request("PUT", "https://example.com/users/7")
req.headers.set("Authorization", "Bearer " + token)
req.writeJson(json.encode(user))
http.Response res = http.send(req)It can be moved, not copied.
Request(string verb, string address)A request for the client, with a copy of the method, as "GET" or "DELETE", and of the whole URL, "https://example.com/users/7". Its headers and its body are added after.
string method: The method, as "GET" or "POST", as the client wrote it.string url: On the server, the target of the request, "/users/7?full=1"; on the client, the whole URL, "https://example.com/users/7?full=1".string path: on the server: the path of the URL, "/users/7", with its escapesstring query: on the server: what follows?, "full=1", with its escapesHeaders headers: in their orderlist<u8> body: the bytes, whole;text()reads them as text
#Request.webSocket
void webSocket(func(ref websocket.Socket) work)On the server: answers 101, turns the request into a WebSocket, and gives it to work, which runs on the task of the connection. When work returns or throws, the connection ends, without the response of the handler. For a clean end, work calls close(), or returns after receive() has thrown websocket.Closed. A request that is not one of WebSocket gets the status 400, and work is not called. The WebSocket has no timeout unless work sets one.
if (req.matches("GET /echo")) {
req.webSocket([](ref websocket.Socket ws) {
for {
switch (ws.receive()) { // websocket.Closed when the client closes
case Text(string text) {
ws.send("echo: " + text)
}
case Binary(list<u8> bytes) {
ws.sendBytes(bytes)
}
}
}
})
}#Request.text
string text() constA copy of the body as text: an exception if it is not UTF-8.
#Request.write
void write(string text)Adds the text at the end of the body, and sets the Content-Type to "text/plain; charset=utf-8" unless the headers have one.
#Request.writeJson
void writeJson(string text)Adds a text of JSON at the end of the body, as req.writeJson(json.encode(user)), and sets the Content-Type to "application/json" unless the headers have one.
#Request.writeBytes
void writeBytes(list<u8> bytes, string type)Adds the bytes at the end of the body, and sets the Content-Type to type, as "image/png", unless the headers have one.
#Request.matches
bool matches(string pattern)Whether the method and the path of the request are those of the pattern, as "GET /users/{id}", where a name in braces takes a segment of the path that is not empty, and {rest...}, only at the end, all the rest of the path. Without the method any method goes, and GET takes HEAD too. The other segments are compared exactly, also a final /; the query does not count. When it is true, param reads the parameters. A pattern with {rest...} before its end is an exception.
#Request.param
string param(string name) constA parameter of the pattern of the last matches that was true, without its escapes: param("id") for "{id}". An exception if that pattern does not have it.
#Request.queryValue
string queryValue(string name) constThe value of a parameter of the query, without its escapes and with + as a space: "2" for queryValue("page") with "?page=2". The first with the name; "" when it is missing or has no value.
#Response
struct ResponseA response of HTTP: on the server, the one that the handler fills, with the status 200 unless it sets another; on the client, the one received, with the whole body.
The server writes it when the handler returns, in one piece with its Content-Length: the Content-Length, Connection and Transfer-Encoding that the handler sets are left out, but "Connection: close" closes the connection after the response. The statuses 204 and 304 send no body, and neither does the response to HEAD.
res.status = 201
res.headers.set("Location", "/users/7")
res.writeJson(json.encode(user))On the client, a body that the server compressed with gzip arrives decompressed, and then the headers have its Content-Length, without Content-Encoding.
http.Response res = http.get("https://example.com/users/7")
if (res.status == 200) {
User user = json.decode<User>(res.text())
}i32 status: as 200, 404 or 500Headers headers: in their orderlist<u8> body: the bytes, whole;text()reads them as text
#Response.text
string text() constA copy of the body as text: an exception if it is not UTF-8.
#Response.write
void write(string text)Adds the text at the end of the body, and sets the Content-Type to "text/plain; charset=utf-8" unless the headers have one.
#Response.writeJson
void writeJson(string text)Adds a text of JSON at the end of the body, as res.writeJson(json.encode(user)), and sets the Content-Type to "application/json" unless the headers have one.
#Response.writeBytes
void writeBytes(list<u8> bytes, string type)Adds the bytes at the end of the body, and sets the Content-Type to type, as "image/png", unless the headers have one.
#Server
struct ServerA server that listens, made by listen or listenTls, and serves once serve is called: until then the connections wait in the system. Its port() is known before, also when 0 asked the system for a free one, so a program can start the server in a task and then call it, as a test does. It can be moved, as into a task, not copied.
http.Server server = http.listen("127.0.0.1", 0)
println("listening on port {}", server.port())
thread.Atomic<i64> count // shared by the requests
server.serve([count](ref http.Request req, ref http.Response res) {
res.write(format("request {}", count.add(1) + 1))
})#Server.port
i32 port() constThe port it listens on, also when 0 asked the system for a free one.
#Server.serve
void serve(const func(ref Request, ref Response) handler) constGives every request to the handler, and never returns. It accepts the connections on the thread or the task that calls it, and serves each one on a task of its own, its requests one after the other while the client keeps it open. So the handler runs on several threads at once: it is a const func, and what the requests share is in a thread.Mutex or a thread.Atomic, captured by reading.
- Before the handler, the request is read whole: a head larger than 64 KiB gets the status 431, a body larger than 16 MiB 413, a request that is not valid 400, and a version other than HTTP/1.1 and 1.0 505. "Expect: 100-continue" is answered.
- The response is written when the handler returns.
- An exception of the handler replaces its response with the status 500 and an empty body, and writes a line on the error output, as "http: GET /users/x: ..."; a panic still ends the program.
- A connection waits 5 seconds for the start of each request, then 30 seconds for each read and write; past them it ends in silence, as it does when the client goes away or the network fails.
- An error in accepting a connection, as too many open files, is tried again after 10 milliseconds.
#Client
struct ClientA client of HTTP that keeps its connections open, up to 8 for each host, to use them again for the next requests to the same host: many requests are much faster. Its methods are const, so several tasks can use the same client at once, capturing it by reading, each request on a connection of its own. A kept connection that the server has closed meanwhile fails before the response: then the request is sent again, once, on a new connection. The destructor closes the connections. It can be moved, not copied.
http.Client client
client.bodyLimit = 1048576
for (i64 id = 1; id <= 3; id++) {
http.Response res = client.get(format("https://example.com/users/{}", id))
println("{}", res.status)
}i64 bodyLimit: The largest body of a response, in bytes, also once decompressed: a larger one is an exception. 16 MiB by default.i64 connectTimeout: How long to wait for a server to take a new connection, with the handshake of TLS, in milliseconds: 30 seconds by default, -1 as long as the system does. Past it the request is an exception that says "timed out".i64 timeout: How long each read and each write of a request waits, in milliseconds: 30 seconds by default, -1 without a limit. It is not the time of the whole request: a large body that keeps arriving goes on.
#Client.get
Response get(string url) constThe response to a GET of the URL, as http.get gives it, on the connections of the client.
#Client.post
Response post(string url, string body, string type) constThe response to a POST of the text body to the URL, with the Content-Type type, as http.post gives it, on the connections of the client.
#Client.send
Response send(Request req) constSends the request as http.send does, on a connection kept by the client or on a new one, which it keeps after the response unless the server closes it. The body of the response has at most bodyLimit bytes.
#Funzioni
#listen
Server listen(string host, i32 port)A server that listens on the port of a name or an address, as "0.0.0.0" for all the addresses of IPv4, and serves once serve is called; port 0 asks the system for a free one, which port() gives. An exception if the name is not found or the port is taken.
#listenTls
Server listenTls(string host, i32 port, string certificate, string key)A server of https, as listen gives: certificate is the text in PEM of its certificate, followed by those of its chain, and key the text in PEM of its private key. An exception if they cannot be read. The handshake of each connection is made on its task.
#serve
void serve(string host, i32 port, const func(ref Request, ref Response) handler)Listens on the port of a name or an address and gives every request to the handler, as listen and then Server.serve do: it never returns. An exception if it cannot listen.
http.serve("0.0.0.0", 8080, [](ref http.Request req, ref http.Response res) {
res.write("Hello!")
})#get
Response get(string url)The response to a GET of the URL, as send gives it.
#post
Response post(string url, string body, string type)The response to a POST of the text body to the URL, with the Content-Type type, as "application/json", as send gives it.
#send
Response send(Request req)Sends the request on a connection of its own, with TLS for https, and gives back the response, read whole. The request is not changed, and can be sent again.
- The URL starts with http:// or https://, and can have a port; a name and a password in it are not supported. Its path and its query are sent as written, so the values in them are written with
escape; the fragment after#is not sent. - The client writes Host, Content-Length and Connection by itself, and adds "User-Agent: cromo" and "Accept-Encoding: gzip" when the request does not have them. It decompresses a body in gzip only when it asked for it.
- Up to ten redirects are followed. After 303, and after 301 or 302 to a method other than GET and HEAD, the request goes on as a GET without a body. Authorization and Cookie are not sent to another host.
- Connecting, with the handshake of TLS, waits at most 30 seconds, and then each read and write as much:
connectTimeoutandtimeoutof aClientchange them. - A status of error, as 404, is a response, not an exception. An exception of type
Erroris a URL that cannot be used, a host that is not found, a failure of the network or of TLS, a timeout, more than ten redirects, an answer that is not HTTP, or a body larger than 16 MiB, also once decompressed.
#escape
string escape(string text)The text with %XX for every byte that is not a letter, a digit, -, _, . or ~, for a value of the query or a segment of the path of a URL: http.escape("a b&c") gives "a%20b%26c".