http: requests over HTTP and HTTPS, event streams, WebSockets
#import "trame:http". Requests over
HTTP or HTTPS with what the system has: WinHTTP on Windows (its proxy settings and certificates), libcurl on Linux, loaded at
run time (libcurl.so.4: a program that never asks for a URL starts on a system without it). Every request blocks: call it
on a thread of its own.
A GET
status, body, err := http.get("https://github.com/me/app/releases/latest/download/update-linux-x64.json",
{max_bytes = 16 * 1024, user_agent = "app/1.2.3", timeout = 30 * time.Second})- Redirects are followed (at most
MAX_REDIRECTS; Windows never follows https to http). statusis the status of the last answer. A status that is not 2xx is no error: the caller reads it (404: no such file).max_bytesbounds the body (0:MAX_BYTES, 64 MiB): a larger one is.Too_Large, and nothing is returned.timeoutbounds the whole request (0:TIMEOUT, 5 minutes).connect_timeoutbounds the name's lookup and the connection, each time one is made (a redirect to another host makes one). 0:timeoutbounds them. A server that does not answer is.Unreachableafter it, not after the wholetimeout.compressed = trueasks for a compressed answer (Accept-Encoding: gzip, deflate,ACCEPT_ENCODING) and gives the body decoded;max_bytesbounds the decoded body. The decoded body's headers say no encoding:Content-Encodingand the encodedContent-Lengthare taken out, on every system (WinHTTP drops them itself once it decodes). AnAccept-Encodingheader inheaderswithcompressedfalse is sent as given, and its body is given as it came.
res, err := http.request("GET", "http://127.0.0.1:4096/session", {compressed = true, connect_timeout = 2 * time.Second})Any request
form, content_type := http.multipart({
http.form_text("reqtype", "fileupload"),
http.form_file("fileToUpload", "shot.png", "image/png", png),
}, context.temp_allocator)
res, err := http.request("POST", "https://example.com/upload", {
headers = {{"Content-Type", content_type}, {"Authorization", "Bearer ..."}},
body = form,
})
defer http.response_destroy(&res)
location, found := http.header_value(res.headers, "Location")request(method, url, req): any method that is a token (GET, POST, PUT, PATCH, DELETE, HEAD...).getis a call of it.Request.headersare sent as given; a header the caller names replaces the client's own (the User-Agent too). Nothing is added to a body: without aContent-Typeheader, none is sent (libcurl's form type and itsExpect: 100-continueare removed).Request.body: nil sends none; POST, PUT and PATCH send an empty one then.- A method that is not a token, a header name that is not a token, or a header value with a line break is
.Bad_Request, before anything is sent. Response:status,body,headers(the last answer's, in order),url(the address that answered, after the redirects),header_text(the lines as received).response_destroyfrees it, with the request's allocator.header_value(headers, name): the first header of that name; names compare without case.- A redirect of a request with a body is followed as browsers do: 303 (and 301, 302 after a POST) becomes a GET.
Connections
request and get keep their connections open and reuse them: the next request to the same server (scheme, host and
port) goes on a connection already made, with no new TCP connection and no new TLS handshake. Nothing to set up and no
client to keep: the pool is the process's, for every thread.
- Several requests at the same time to one server use one connection each; after them, those connections are reused.
- Linux: at most
POOL_IDLE(8) idle libcurl handles wait, each with libcurl's connections (5 at most; one idle for more than 118 s is not reused). Windows: one WinHTTP session for the process, which pools its connections by server. - A connection that the server or a tunnel closed while it waited is found closed by the client, which connects again.
- An event stream (
events) and a WebSocket hold a connection of their own for their whole life. A body received in chunks (receive) takes its connection from the pool on Linux, asrequestdoes.
A body received in chunks
on_part :: proc(user: rawptr, p: http.Body_Part) -> http.Keep_Going {
w := (^fsx.Writer)(user)
if !fsx.writer_append(w, p.bytes) { return .Stop } // p.bytes is valid during the call only
// p.received of p.length (-1: not known): post it to the interface's thread
return .Continue
}
stop: http.Stop // another thread: http.stop_ask(&stop)
res, err := http.receive("GET", url, {headers = {{"Authorization", auth}}}, on_part, &writer, &stop)
defer http.response_destroy(&res)receive(method, url, req, on_part, user, stop)gives the answer's body toon_partchunk by chunk and keeps none of it: a file of any size takes the memory of one chunk. It blocks: call it on a worker.on_partruns on that thread (Linux: from libcurl's call, withruntime.default_context()); it never runs on the interface's thread.Body_Part:bytes, the answer'sstatus, the bytesreceivedso far (this chunk's included) and the body'slength(its Content-Length; -1 when there is none, or withreq.compressed, whose chunks come decoded).- It ends when the body is whole, when
on_partreturns.Stop(.None: what came stands), or whenstop_ask(&stop)is called from another thread (seen within about a second:.Stopped). req.timeoutis the longest silence, not the whole transfer (0:STREAM_SILENCE): a download of any length goes on while bytes come. A silence is.Unreachable.req.max_bytesbounds the body only when it is above 0 (past it:.Too_Large); the default is no bound, as nothing is kept.- A status that is not 2xx gives no chunk and no error: read
res.status(a 404 page never reaches a file). The answer is the last one, after the redirects;reshas its status, its headers and its address, never a body (response_destroyfrees it). With an error,resis empty. - A body is sent as
requestsends it (req.body,req.headers);req.no_redirectsandreq.connect_timeouttoo. fsx.Writer(docs/fsx.md) writes the chunks to a temporary file and renames it over the target at the end.
Form bodies
Pure procedures: no system call, testable anywhere.
multipart(fields)gives amultipart/form-databody and itsContent-Typewith the boundary. AForm_Fieldis a text (form_text(name, value)) or a file (form_file(name, file_name, content_type, bytes); an empty content type isapplication/octet-stream). The boundary is random and occurs in no field. A quote or a line break in a name or file name is written%22,%0D,%0A, as browsers do.form_urlencoded(params)gives anapplication/x-www-form-urlencodedbody fromParams:a=1&b=x+y.query_append(url, params)adds params to a URL's query string (?or&, before a fragment).form_encode(s)encodes one name or value: letters, digits and*-._stay, a space is+, any other byte is%XX.component_encode(s)encodes one part of a URL (a path's segment, a query's value outside a form): RFC 3986's unreserved characters (letters, digits,-._~) stay, any other byte is%XX(a space%20, a slash%2F).
A server's event stream
on_event :: proc(user: rawptr, e: http.Event) -> http.Keep_Going {
fmt.println(e.type, e.data) // e's strings are valid during the call only
return .Continue
}
stop: http.Stop // another thread: http.stop_ask(&stop)
status, err := http.events("https://host/event", {headers = {{"Authorization", auth}}}, on_event, nil, &stop)events(url, req, on_event, user, stop)reads a Server-Sent Events stream (GET) until the server ends it,on_eventreturns.Stop, orstop_ask(&stop)is called from another thread (seen within about a second:.Stopped). Call it on a worker.Event:type("message"when the stream names none),data(thedata:lines joined by\n),id(the lastid:of the stream),retry(the lastretry:, in milliseconds; 0: none).req.timeoutis the longest silence, not the whole stream (0:STREAM_SILENCE, 2 minutes). Any byte restarts it: a server's heartbeat comment is enough. A silence is.Unreachable.req.max_bytesbounds one line and one event.req.connect_timeoutbounds the connection (0: the silence does).req.compressedasks for a compressed stream, decoded as it comes.- An
Accept: text/event-streamheader is added whenreq.headershas no Accept. - A status that is not 2xx gives no event and no error: read
status. The end of the stream is no error either. There is no reconnection: calleventsagain, with aLast-Event-IDheader from the lastEvent.id, afterEvent.retry. Event_Parser(event_parser_init,event_parser_feed,event_parser_destroy) is the parser alone: bytes in any cut, the WHATWG rules (LF, CRLF or CR; comments; one space after the colon dropped; an event with no data line not given).
WebSockets
s, err := http.ws_connect("wss://host/socket", {headers = {{"Authorization", auth}}})
if err != .None { return }
defer http.ws_close(s)
http.ws_send(s, transmute([]u8)string(`{"hello":1}`)) // any thread
for {
m, e := http.ws_recv(s) // the reader's thread
if e != .None || m.kind == .Close { break }
handle(m.data) // valid until the next ws_recv
}ws_connect(url, req):ws://orwss://.req.headersgo with the handshake;req.timeoutbounds the handshake,req.connect_timeoutits connection (0:timeout);req.max_bytesbounds one message;req.compresseddoes nothing (a handshake has no body). A server that answers without the upgrade is.Refused.ws_recv(s, wait): the next whole message,.Textor.Binary; a ping is answered with a pong.wait= 0 waits without limit; when a wait runs out,.Timed_Out, and the socket stays open. The server's close is a.Closemessage (code, the reason indata); the calls after it are.Closed.ws_send(s, data, kind):.Text(the default) or.Binary, from any thread, one at a time.ws_stop(s), from any thread: a waitingws_recvreturns.Stoppedat once, and every call after it too.ws_close(s): sends the close (1000) if the socket is open and frees it. Call it on the reader's thread, after its lastws_recv, when no other thread uses the socket.- Windows: WinHTTP's WebSocket. Linux: any libcurl (7.18.1 or later), with or without its own WebSocket API: curl makes the connection (TLS, a proxy as a tunnel), the package writes the upgrade and the frames.
- Linux: a
ws://socket to a loopback address written as such (127.x.x.x,[::1]) needs no libcurl: the package makes the TCP connection itself (no TLS and no proxy apply there).trame:cdpconnects there, so a program's tools drive it in a shell without curl.ws://localhostis a name: libcurl looks it up. - A frame that breaks the protocol (masked by the server, an unknown opcode) ends the socket:
.Closed.
Errors
Error: No_Client (Linux without libcurl), Bad_Url (not http or https, credentials in the address), Bad_Request,
Unreachable (the name, the network, TLS, the time limit), Too_Large; for streams and sockets Stopped, Timed_Out,
Closed and Refused (no upgrade, or a wrong Sec-WebSocket-Accept). error_text says it in a sentence.
url_parse gives the parts of an http or https URL (secure, host, port, path with its query).
The Updater (docs/update.md) downloads with it.