cromo La guida di Cromo
Scarica PDF EN

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.

cromo
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.

cromo
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

cromo
struct Header

A header of a request or of a response.

  • string name: "Content-Type", in the case it was written in
  • string value: "text/html"; one received has no spaces around it

#Headers

cromo
struct Headers

The 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.

cromo
res.headers.set("Cache-Control", "no-store")
string agent = req.headers.get("user-agent")  // "" without it
  • list<Header> items: in their order, also those with the same name

#Headers.get

cromo
string get(string name) const

A copy of the value of the first header with the name, "" without one.

#Headers.has

cromo
bool has(string name) const

Whether there is a header with the name, also with an empty value.

#Headers.set

cromo
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

cromo
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

cromo
void remove(string name)

Removes all the headers with the name; none is not an error.

#Request

cromo
struct Request

A 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:

cromo
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:

cromo
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.

cromo
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 escapes
  • string query: on the server: what follows ?, "full=1", with its escapes
  • Headers headers: in their order
  • list<u8> body: the bytes, whole; text() reads them as text

#Request.webSocket

cromo
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.

cromo
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

cromo
string text() const

A copy of the body as text: an exception if it is not UTF-8.

#Request.write

cromo
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

cromo
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

cromo
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

cromo
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

cromo
string param(string name) const

A 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

cromo
string queryValue(string name) const

The 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

cromo
struct Response

A 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.

cromo
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.

cromo
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 500
  • Headers headers: in their order
  • list<u8> body: the bytes, whole; text() reads them as text

#Response.text

cromo
string text() const

A copy of the body as text: an exception if it is not UTF-8.

#Response.write

cromo
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

cromo
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

cromo
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

cromo
struct Server

A 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.

cromo
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

cromo
i32 port() const

The port it listens on, also when 0 asked the system for a free one.

#Server.serve

cromo
void serve(const func(ref Request, ref Response) handler) const

Gives 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

cromo
struct Client

A 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.

cromo
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

cromo
Response get(string url) const

The response to a GET of the URL, as http.get gives it, on the connections of the client.

#Client.post

cromo
Response post(string url, string body, string type) const

The 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

cromo
Response send(Request req) const

Sends 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

cromo
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

cromo
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

cromo
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.

cromo
http.serve("0.0.0.0", 8080, [](ref http.Request req, ref http.Response res) {
    res.write("Hello!")
})

#get

cromo
Response get(string url)

The response to a GET of the URL, as send gives it.

#post

cromo
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

cromo
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: connectTimeout and timeout of a Client change them.
  • A status of error, as 404, is a response, not an exception. An exception of type Error is 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

cromo
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".