Skip to content
Weaverv0.5.0

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.

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.post and Http.send open 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 Response whose isSuccess() is false. The errors are those of the exchange: BadUrl, Malformed, TooLarge, Closed, and IoError for the network, a timeout included.
  • Each takes tls:, a TlsConfig.client(roots:) for another set of certificate authorities than the system’s, and timeout:.

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.

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()))!

A body is held in memory, 8 MiB at most by default, setMaxBody to change it. Past that, stream it:

  • c.stream(req) and Http.stream return a StreamedResponse whose body is read as it arrives;
  • sendFrom(req, reader) and streamFrom send a body from a Reader, a file for instance, without loading it.

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, its headers and body.
  • 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; setMaxBody and setTimeout, one minute per read or write by default, bound what a client may hold.
  • serveStream passes the body as a BodyReader instead, 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()

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.