Rust · Quickstart

Quickstart

1.0.0-rc.1 · 60202332

A server answers on one or more interfaces, and a client calls it; neither starts a thread.

use ucall::*;

let mut server = Server::new(&[Interface::new("127.0.0.1:0")])?;
server.get("/hello/{name}", |request: Request| {
    let name = request.path_parameter("name").unwrap_or_default();
    let greeting = [b"Hello, ", name].concat();
    let _ = request.reply(HTTPStatus::OK, &["content-type: text/plain".into()], &greeting);
})?;
let address = server.address(0).unwrap().to_owned();

let mut client = Client::new(ClientOptions { connections: 1, ..Default::default() })?;
std::thread::scope(|scope| {
    scope.spawn(|| server.take_calls(0));
    let response = client.get(format!("http://{address}/hello/world"));
    server.stop();
    assert_eq!(response?.body(), b"Hello, world");
    Ok::<(), Error>(())
})?;

The polling thread runs the handler, the client blocks in get until its response arrives, and stop releases the polling thread so the scope can end.