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:
| Request | Answer |
|---|---|
/whoami with authorization: Bearer ann | 200, ann |
/whoami with no header | 400, "`authorization` is missing" |
/whoami with authorization: Basic YW5u | 400, and the detail names authorization |
/whoami-or-guest with no header | 200, guest |
/whoami-or-guest with Basic x | 400 |
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_callreads the transport's context. On HTTP it is&HttpCx, which gives headers, URI, route, path parameters, client address and the body slot.CONSUMES_BODYistruefor an extractor that takes the body throughcx.take_body(). The macro then counts it against the one-body rule, and two readers fail to compile with both parameters named.dependenciesdeclares 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
HttpCxis itself a parameter:fn handler(&self, cx: HttpCx).- Container types (
Dep<T>,Ext<T>,ExecutionRef) are accepted on every transport and need noFromCall.Ext<T>reads a value an earlier stage wrote withcx.extensions().insert(..), a guard for example. - A handler that wants the same extractor on another transport implements
FromCallfor that transport's marker as well.FromCallis generic over the transport; the HTTP, RPC, WebSocket and gRPC crates each define theirs.