Skip to main content

Module socket

Module socket 

Source
Expand description

HTTP server and client utilities, selectively compiled via Cargo features.

This module exposes two sub-modules behind feature flags:

Sub-moduleFeature flag(s)
serversocket or socket-server
clientsocket or socket-client

Enable socket to get both, or opt into only one side with socket-server / socket-client.

§Server

Build typed HTTP routes using a fluent builder chain starting from server::ServerMechanism. Routes are registered on a server::Server and served with a single .await. For runtime address migration or live route insertion, use server::Server::serve_managed which returns a server::BackgroundServer handle (see server::BackgroundServer::rebind and server::BackgroundServer::mechanism).

The chain supports:

  • No extras — handler receives no arguments
  • JSON body — via .json::<T>(), handler receives T: DeserializeOwned
  • Query params — via .query::<T>(), handler receives T: DeserializeOwned
  • Authenticated-encrypted body — via .encryption::<T>(key), body is decrypted before delivery
  • Authenticated-encrypted query — via .encrypted_query::<T>(key), query is decrypted before delivery
  • Shared state — via .state(s), handler receives a clone of S
  • State + body / State + query — any of the above combined with .state(s)

Each branch finalises with .onconnect(async handler) or the unsafe .onconnect_sync(sync handler). Use the [reply!] macro (or standalone helpers) to construct the response.

The server::mechanism attribute macro is an ergonomic shorthand for the full builder call: #[mechanism(server, POST, "/items", json)] on an async fn is exactly equivalent to writing server.mechanism(ServerMechanism::post("/items").json::<T>().onconnect(handler)).


let store: Arc<Mutex<Vec<Item>>> = Arc::new(Mutex::new(vec![]));

let mut server = Server::default();
server
    .mechanism(
        ServerMechanism::get("/health")
            .onconnect(|| async { reply!() })
    )
    .mechanism(
        ServerMechanism::post("/items")
            .json::<NewItem>()
            .onconnect(|body| async move {
                let item = Item { id: 1, name: body.name };
                reply!(json => item, status => Status::Created)
            })
    )
    .mechanism(
        ServerMechanism::get("/items")
            .state(store.clone())
            .onconnect(|state| async move {
                let items = state.lock().unwrap().clone();
                reply!(json => items)
            })
    )
    .mechanism(
        ServerMechanism::get("/items/search")
            .query::<Filter>()
            .onconnect(|filter| async move {
                let _ = filter.page;
                reply!()
            })
    );

// server.serve(([0, 0, 0, 0], 8080)).await;

§Client

Make typed HTTP requests using a fluent builder chain starting from client::Client. The full URL is constructed automatically from a client::Target (localhost port or remote URL) and the endpoint string. Both async (.send()) and sync (.send_sync()) are supported.

The chain supports:

  • Plain — no body, no query
  • JSON body — via .json(value), serialises with serde
  • Query params — via .query(value), serialised into the URL query string

All seven HTTP methods are available: get, post, put, delete, patch, head, options.


let client = Client::new_async(Target::Localhost(8080));

// ── GET /items ───────────────────────────────────────────────────────────
// Server:
//   ServerMechanism::get("/items")
//       .onconnect(|| async {
//           let items: Vec<Item> = vec![];
//           reply!(json => items)
//       })
let items: Vec<Item> = client.get("/items").send().await?;

// ── POST /items  (JSON body) ──────────────────────────────────────────────
// Server:
//   ServerMechanism::post("/items")
//       .json::<NewItem>()
//       .onconnect(|body| async move {
//           let item = Item { id: 1, name: body.name };
//           reply!(json => item, status => Status::Created)
//       })
let created: Item = client
    .post("/items")
    .json(NewItem { name: "widget".to_string() })
    .send()
    .await?;

// ── GET /items  (query params) ────────────────────────────────────────────
// Server:
//   ServerMechanism::get("/items")
//       .query::<Filter>()
//       .onconnect(|filter| async move {
//           let _ = filter.page;
//           reply!(json => Vec::<Item>::new())
//       })
let page: Vec<Item> = client
    .get("/items")
    .query(Filter { page: 2 })
    .send()
    .await?;

// ── DELETE /items/1  (sync) ───────────────────────────────────────────────
// Server:
//   ServerMechanism::delete("/items/1")
//       .onconnect(|| async {
//           reply!(message => toolkit_zero::socket::server::EmptyReply, status => Status::NoContent)
//       })
let _: Item = client.delete("/items/1").send_sync()?;

Modules§

backend_deps
Re-exports all backend dependencies used by the socket module and its sub-modules (server, client).
client
Typed, fluent HTTP client.
prelude
Convenience re-exports for the socket module.
server
Typed, fluent HTTP server construction.

Enums§

SerializationKey
Controls which ChaCha20-Poly1305 key is used when the body or query parameters are sealed.