HTTP clients and servers
Module weaver.net.http: its API, wv doc weaver.net.http.
weaver.net.http speaks HTTP/1.1, plain or over TLS, as a client and as a
server, over the sockets of weaver.net. It gives requests and responses,
not routing: weft/rest builds services on it, weft/websocket WebSocket.
A request
Section titled “A request”import weaver.net.http.{Http}
val r = Http.get("https://example.com/")!if r.isSuccess() { print(r.bodyText() ?? "") }
val created = Http.post("https://api.example.com/notes", "hello".bytes(), "text/plain")!Http.get,Http.postandHttp.sendopen a connection for the request and close it after. Redirects are returned as they are, a 3xx.- A status is no error: a 404 is a
ResponsewhoseisSuccess()is false. The errors are those of the exchange:BadUrl,Malformed,TooLarge,Closed, andIoErrorfor the network, a timeout included. - Each takes
tls:, aTlsConfig.client(roots:)for another set of certificate authorities than the system’s, andtimeout:.
A Request is built and filled in for anything else:
val req = mut Request.new("PUT", Url.parse("https://api.example.com/notes/1").unwrap())req.headers.set("Authorization", "Bearer ${token}")req.headers.set("Content-Type", "application/json")req.body = text.bytes()val r = Http.send(req)!Headers compare names without case; get gives the first value,
getAll each, set replaces, add appends.
Several requests on one connection
Section titled “Several requests on one connection”HttpConnection keeps its connection between requests, as long as the
server keeps it open, isOpen(): a resource, held with using.
using c = HttpConnection.open(Url.parse("https://example.com").unwrap())!val home = c.send(Request.new("GET", Url.parse("https://example.com/").unwrap()))!val about = c.send(Request.new("GET", Url.parse("https://example.com/about").unwrap()))!Large bodies
Section titled “Large bodies”A body is held in memory, 8 MiB at most by default, setMaxBody to change
it. Past that, stream it:
c.stream(req)andHttp.streamreturn aStreamedResponsewhosebodyis read as it arrives;sendFrom(req, reader)andstreamFromsend a body from aReader, a file for instance, without loading it.
A server
Section titled “A server”HttpServer.bind listens; serve runs each connection in a task of its
own, and passes each request, its body read, to the handler, until the
task calling it is cancelled.
import weaver.net.http.{HttpServer, Request, Response}
fn main() ! { using server = HttpServer.bind("0.0.0.0:8080")! server.serve(req => match req.url.path { "/" => Response.text(200, "hello") _ => Response.text(404, "nothing here") })!}Response.text(status, text)answers text;Response.new(status)is filled in like a request, itsheadersandbody.Response.file(200, path)sends a file as it is read, whatever its size.- An invalid request gets 400, too large a body 413, without reaching the
handler;
setMaxBodyandsetTimeout, one minute per read or write by default, bound what a client may hold. serveStreampasses the body as aBodyReaderinstead, for uploads larger than memory.HttpServer.bind(addr, tls: TlsConfig.server(cert: "cert.pem", key: "key.pem")!)serves HTTPS.
A server meant to stop, in a test, listens on port 0, which picks a free
one that localAddr() gives, and serves in a task its caller cancels:
async fn run(using server: HttpServer, handler: (Request) => Response): () ! IoError { server.serve(handler)!}
using server = HttpServer.bind("127.0.0.1:0")!val base = "http://${server.localAddr()!}"using served = run(server, req => Response.text(200, "ok"))val r = Http.get("${base}/")!served.cancel()Taking the connection over
Section titled “Taking the connection over”Response.upgrade(headers, conn => …) answers 101, then hands the
connection to the function, which reads and writes it as it likes;
client side, HttpConnection.upgrade(req) does the same. WebSocket is
built that way, in weft/websocket.