ulo
ulo
Documentation

Start here

Coming from NestJSNestJS topics, mapped

The model

ExtractorsBuilt-in ExtractorsValidationCustom ExtractorsMultipart

Protocols

Integrations

Operating

Reference

Extractors

Built-in Extractors

The HTTP extractors, what each reads, and the status each answers when the call does not fit.

The code on this page is from examples/15-http-requests.

use ulo::{controller, handlers};
use ulo_http::headers::UserAgent;
use ulo_http::{Created, Header, Json, Path, Query, Valid, WithHeaders};

#[handlers]
impl NotesController {
    #[ulo_http::post("/notes")]
    fn create(&self, Valid(Json(new)): Valid<Json<NewNote>>) -> Created<Json<Note>> { /* .. */ }

    #[ulo_http::get("/notes/{id}")]
    fn find(&self, Path(id): Path<u32>) -> Found { /* .. */ }

    #[ulo_http::get("/notes")]
    fn list(&self, Query(page): Query<Page>) -> WithHeaders<Json<Vec<Note>>> { /* .. */ }

    #[ulo_http::get("/agent")]
    fn agent(&self, agent: Header<UserAgent>) -> String { /* .. */ }
}

NotesController is a #[controller] struct; NewNote, Page, Note and Found (Result<Json<Note>, NoteNotFound>) are the example's own types. A handler is a method. One without &self (or self: Arc<Self>) is refused at compile time.

The extractors

TypeReadsConsumes the body
Path<T>the route's {param} segments, as a struct by field name, a tuple by position, or a scalarno
Query<T>the query stringno
Json<T>a JSON body: application/json or any +json media typeyes
Form<T>an application/x-www-form-urlencoded bodyyes
Bytesthe whole bodyyes
BodyStreamthe body as a stream of chunksyes
Multiparta multipart/form-data body, part by part; see Multipartyes
Header<H>one typed header from the headers crate, such as ulo_http::headers::UserAgentno
HeaderMapall the request headersno
LastEventIdthe Last-Event-ID header an SSE client sends on reconnect; see Streamingno
HttpCxthe call's context: head, method, URI, route, client addressno
Host<T>a value a middleware put in the requestno

Path<T> is checked against its route at startup. A field the route does not name, a tuple of the wrong length, or a scalar on a route with other than one parameter is a startup error, not the first request's. A map, a #[serde(flatten)] struct and a hand-written Deserialize that calls deserialize_any ask for no names and are not checked.

Reading the body as it arrives

BodyStream yields chunks without holding the body whole. This handler counts what arrives (examples/15-http-requests/src/intake.rs):

#[ulo_http::post("/count")]
async fn count(&self, mut body: BodyStream) -> Result<String, BoxError> {
    let (mut chunks, mut bytes) = (0, 0);
    while let Some(chunk) = body.next().await {
        chunks += 1;
        bytes += chunk?.len();
    }
    Ok(format!("{bytes} bytes in {chunks} chunks"))
}

next comes from futures_util::StreamExt. A stream that passes the body limit fails with a 413-class ExtractError::TooLarge (When extraction fails).

Forms

#[derive(Deserialize)]
pub struct Login {
    pub user: String,
    pub pw: String,
}

#[ulo_http::post("/login")]
fn login(&self, Form(login): Form<Login>) -> String { /* .. */ }

JSON sent to a Form handler answers 415, and a form missing pw answers 422: it decodes, and it does not fit.

When extraction fails

Every extractor fails with the same ExtractError, flat, each variant carrying the parameter's name. It is classified into an ErrorKind and rendered as problem details.

VariantMeaningHTTP
Missinga required header, query field, path segment, or a body that is empty400
Malformedcould not be decoded: wrong syntax, or cut off400
Mismatcheddecoded, and does not fit the type422
UnsupportedMediaTypewrong Content-Type415, with Accept naming the media type expected
TooLargeover the body limit (max_body)413
Invalidvalidation rules failed; see Validation422
BodyTakena guard or interceptor took the body first500, message withheld
HostMissingno value for Host<T>; a deployment fault500, message withheld
Overfloweda streamed body's unread items passed the transport's bound503
OverflowedBytesa streamed body's unread items passed the transport's byte bound503

What examples/15-http-requests/tests/requests.rs asserts:

  • {not json is a 400 whose detail starts with "`body` could not be decoded", and text/plain is a 415 with accept: application/json.
  • GET /notes/seven for a Path<u32> is a 400, and the handler never runs.
  • GET /notes?limit=lots is a 400, and GET /agent with no user-agent is a 400 with detail "`user-agent` is missing".

A Query<T> or Path<T> value that does not parse is 400 where a body that does not fit is 422: the query and the path are the request's target rather than its content.

An error handler reaches the original failure with err.downcast_ref::<CallError>()?.source_as::<ExtractError>().

Option<T>

Option<E> of an extractor is None only for a missing value. A value that is present and wrong still fails. Caller here is the extractor written on Custom Extractors:

#[ulo_http::get("/whoami-or-guest")]
fn whoami_or_guest(&self, caller: Option<Caller>) -> String {
    caller.map_or_else(|| "guest".to_owned(), |Caller(name)| name)
}

With no Authorization header this answers guest. With Basic x it answers 400: the header is present and does not parse. For Option<Json<T>>, None is an empty body.

One body, checked at compile time

Two parameters that both consume the body fail to compile, and the error names both:

fn create(&self, note: Json<String>, raw: Bytes) -> String // does not compile

The check reads a constant each extractor declares, so it holds for aliases, for wrappers such as Valid<Json<T>> and Option<Json<T>>, and for extractors you write. A guard or interceptor that takes the body itself with cx.take_body() is the case the compiler cannot see: the extractors then fail with BodyTaken.

Extractors

Handler parameters that read the call, checked when the application is built.

Validation

Declarative rules on a request type, checked by Valid before the handler runs.

On this page

The extractorsReading the body as it arrivesFormsWhen extraction failsOption<T>One body, checked at compile time