ulo
ulo
Documentation

Start here

IntroductionInstallationQuick StartProject StructureDevelopment Workflow
Coming from NestJSNestJS topics, mapped

The model

Protocols

Integrations

Operating

Reference

Getting Started

Quick Start

One module, one controller and one route, served on tokio and hyper.

This page builds examples/01-hello in one file. It needs Rust 1.88 or later.

Create the project

cargo new hello
cd hello

Replace Cargo.toml with the dependencies from Installation, and set the edition:

Cargo.toml
[package]
name = "hello"
version = "0.1.0"
edition = "2024"

[dependencies]
ulo = "=0.1.0-alpha.3"
ulo-http = "=0.1.0-alpha.3"
ulo-http-hyper = "=0.1.0-alpha.3"
ulo-runtime-tokio = "=0.1.0-alpha.3"
tokio = { version = "1", features = ["macros", "rt-multi-thread"] }

Write the application

src/main.rs
use ulo::{App, controller, handlers, module};
use ulo_http_hyper::Server;
use ulo_runtime_tokio::{Tokio, shutdown_signal};

#[controller]
pub struct HelloController;

#[handlers]
impl HelloController {
    #[ulo_http::get("/")]
    fn hello(&self) -> &'static str {
        "Hello, ulo!"
    }
}

#[module(controllers = [HelloController])]
pub struct AppModule;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let app = App::builder(AppModule)
        .runtime(Tokio::current())
        .wire()?
        .connect()
        .await?
        .bind(Server::new("127.0.0.1:3000"))
        .listen()
        .await?;
    for bound in app.addresses() {
        println!("listening on http://{}", bound.addr);
    }
    app.serve(shutdown_signal()).await?;
    Ok(())
}

The example splits this across src/lib.rs (the controller, the module and a builder() function) and src/main.rs, so its tests can start the same application on another port. main there also reads the port from PORT.

Run it

cargo run
curl http://127.0.0.1:3000/
# Hello, ulo!

Ctrl-C ends the process: shutdown_signal() resolves on SIGINT or SIGTERM, and serve then drains in-flight requests and returns.

What each part does

  • #[controller] makes HelloController a struct the container can build and marks it as a dispatch target. A service is declared with #[injectable] instead.
  • #[handlers] marks the impl whose methods are handlers. #[ulo_http::get("/")] names the transport and the route. A handler that returns a &'static str answers 200 with that text.
  • #[module(controllers = [HelloController])] binds the controller. Modules also take imports, providers and exports; see Core Concepts.
  • App::builder(AppModule).runtime(Tokio::current()) names the runtime. wire() checks the module graph and reports every problem at once. connect() builds the providers and runs their hooks. bind(Server::new(..)) registers the HTTP server, listen() acquires its socket, and serve(..) runs until the signal future resolves.
  • app.addresses() returns the addresses bound, so Server::new("127.0.0.1:0") reports the port the operating system chose.

Add a service and typed requests

A handler names what it needs in its signature. A provider is injected as Dep<T>, and extractors read and validate the request. This is examples/15-http-requests trimmed to two routes; it also needs serde with the derive feature in Cargo.toml.

use std::sync::Mutex;

use serde::{Deserialize, Serialize};
use ulo::{Dep, controller, handlers, injectable, module};
use ulo_http::{Created, Json, Query, Valid, Validate};

#[derive(Clone, Serialize)]
pub struct Note {
    pub id: u32,
    pub title: String,
}

#[derive(Deserialize, Validate)]
pub struct NewNote {
    #[validate(length(min = 1, max = 20))]
    pub title: String,
}

#[derive(Deserialize)]
pub struct Page {
    pub limit: Option<usize>,
}

#[injectable]
pub struct Notes {
    #[injectable(default)]
    all: Mutex<Vec<Note>>,
}

#[controller]
pub struct NotesController {
    notes: Dep<Notes>,
}

#[handlers]
impl NotesController {
    #[ulo_http::post("/notes")]
    fn create(&self, Valid(Json(new)): Valid<Json<NewNote>>) -> Created<Json<Note>> {
        let mut all = self.notes.all.lock().unwrap();
        let note = Note { id: all.len() as u32 + 1, title: new.title };
        all.push(note.clone());
        Created::at(format!("/notes/{}", note.id), Json(note))
    }

    #[ulo_http::get("/notes")]
    fn list(&self, Query(page): Query<Page>) -> Json<Vec<Note>> {
        let all = self.notes.all.lock().unwrap();
        Json(all.iter().take(page.limit.unwrap_or(usize::MAX)).cloned().collect())
    }
}

#[module(providers = [Notes], controllers = [NotesController])]
pub struct NotesModule;

#[injectable(default)] on a field gives the service its own state instead of an injected dependency. Created::at answers 201 with a Location header. A title outside 1 to 20 characters is refused with 422 before the handler runs. Validate is the derive that reads the #[validate(..)] attributes, and Valid<..> is the extractor wrapper that runs it; both come from ulo_http.

To serve it, import NotesModule from AppModule:

#[module(imports = [NotesModule], controllers = [HelloController])]
pub struct AppModule;

A module lists the modules it imports under imports, as examples/03-traits-and-qualifiers does with imports = [DbModule].

The extractors, validation and typed errors are covered in Extractors.

The same application on smol

examples/22-http-on-smol is example 01 with the runtime and listener swapped. The module and controller are unchanged, and Cargo.toml takes the smol dependencies from Installation. main differs in the runtime, the server type and the signal future. The example calls its own builder() and server(..) helpers where this listing writes their bodies out:

src/main.rs
use std::sync::Arc;

use async_signal::{Signal as Os, Signals};
use futures_util::StreamExt;
use ulo::{App, Signal};
use ulo_http_hyper::ServerOn;
use ulo_listener_smol::SmolListener;
use ulo_runtime_smol::{Executor, Smol};

/// Resolves on the first SIGINT or SIGTERM.
async fn shutdown_signal() -> Signal {
    let mut signals = Signals::new([Os::Int, Os::Term]).expect("the signal handlers install");
    match signals.next().await {
        Some(Ok(Os::Term)) => Signal::new("SIGTERM"),
        _ => Signal::new("SIGINT"),
    }
}

fn main() -> Result<(), ulo::BoxError> {
    let smol = Smol::new(Arc::new(Executor::new()));
    smol.block_on(async {
        let app = App::builder(AppModule)
            .runtime(smol.clone())
            .wire()?
            .connect()
            .await?
            .bind(ServerOn::<SmolListener>::new("127.0.0.1:3000"))
            .listen()
            .await?;
        for bound in app.addresses() {
            println!("listening on http://{}", bound.addr);
        }
        app.serve(shutdown_signal()).await?;
        Ok(())
    })
}

ServerOn::<SmolListener> is the hyper server over the smol listener. Nothing in the application runs on tokio's runtime; hyper pulls in only tokio's synchronisation primitives.

Next

  • Project Structure: the larger starting point ulo new writes.
  • Core Concepts: modules, providers, scopes.
  • Request Lifecycle: guards, interceptors and error handlers.

Installation

Dependency lines for a tokio or smol application, Rust versions per crate, and installing the CLI.

Project Structure

The files ulo new writes, how its main wires an application, and where new modules go.

On this page

Create the projectWrite the applicationRun itWhat each part doesAdd a service and typed requestsThe same application on smolNext