ulo
ulo
Documentation

Start here

Coming from NestJSNestJS topics, mapped

The model

ExtractorsBuilt-in ExtractorsValidationCustom ExtractorsMultipart

Protocols

Integrations

Operating

Reference

Extractors

Custom Extractors

Implement FromCall to give handlers a parameter type of your own.

An extractor is a type that implements FromCall<T> for a transport. Implement it for anything the built-in set does not read, such as a header with a scheme of your own, and a handler can take the type. The example is Caller in examples/15-http-requests/src/intake.rs.

use ulo_http::{ExtractError, FromCall, Http, HttpCx};

/// The caller named by `authorization: Bearer <name>`. `FromCall<Http>` is the whole contract: a
/// missing header is `Missing`, which `Option<Caller>` turns into `None`, and any other scheme is
/// `Malformed`, which it does not.
pub struct Caller(pub String);

impl FromCall<Http> for Caller {
    async fn from_call(cx: &HttpCx) -> Result<Self, ExtractError> {
        let param = "authorization";
        let value = cx.headers().get(param).ok_or(ExtractError::Missing { param })?;
        match value.to_str().ok().and_then(|text| text.strip_prefix("Bearer ")) {
            Some(name) => Ok(Caller(name.to_owned())),
            None => Err(ExtractError::Malformed { param, source: cx.app().redact(Box::new(NotBearer)) }),
        }
    }
}
#[ulo_http::get("/whoami")]
fn whoami(&self, Caller(name): Caller) -> String {
    name
}

#[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)
}

NotBearer is the example's private error type for the wrong scheme. tests/intake.rs asserts the results:

RequestAnswer
/whoami with authorization: Bearer ann200, ann
/whoami with no header400, "`authorization` is missing"
/whoami with authorization: Basic YW5u400, and the detail names authorization
/whoami-or-guest with no header200, guest
/whoami-or-guest with Basic x400

The trait

pub trait FromCall<T: Transport>: Sized + Send + 'static {
    const CONSUMES_BODY: bool = false;
    fn dependencies(_d: &mut Dependencies) {}
    fn from_call(cx: &T::Cx) -> impl Future<Output = Result<Self, ExtractError>> + Send;
}
  • from_call reads the transport's context. On HTTP it is &HttpCx, which gives headers, URI, route, path parameters, client address and the body slot.
  • CONSUMES_BODY is true for an extractor that takes the body through cx.take_body(). The macro then counts it against the one-body rule, and two readers fail to compile with both parameters named.
  • dependencies declares what the extractor reads from the container, so the wiring pass checks it like any constructor's.

Failing

Return the ExtractError variant that says what went wrong. The variant decides the status (the table), and each carries the parameter's name so the response names it.

Malformed and Mismatched carry a source built through cx.app().redact(..), which runs the application's redaction over the decoder's error, so a secret in a malformed value never reaches the response.

Option<Caller> is None for Missing and HostMissing only. A Malformed value still fails, since the value is present.

Other parameter types

  • HttpCx is itself a parameter: fn handler(&self, cx: HttpCx).
  • Container types (Dep<T>, Ext<T>, ExecutionRef) are accepted on every transport and need no FromCall. Ext<T> reads a value an earlier stage wrote with cx.extensions().insert(..), a guard for example.
  • A handler that wants the same extractor on another transport implements FromCall for that transport's marker as well. FromCall is generic over the transport; the HTTP, RPC, WebSocket and gRPC crates each define theirs.

Validation

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

Multipart

Read file uploads part by part, under a server body limit and a tighter per-route one.

On this page

The traitFailingOther parameter types