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
| Type | Reads | Consumes the body |
|---|---|---|
Path<T> | the route's {param} segments, as a struct by field name, a tuple by position, or a scalar | no |
Query<T> | the query string | no |
Json<T> | a JSON body: application/json or any +json media type | yes |
Form<T> | an application/x-www-form-urlencoded body | yes |
Bytes | the whole body | yes |
BodyStream | the body as a stream of chunks | yes |
Multipart | a multipart/form-data body, part by part; see Multipart | yes |
Header<H> | one typed header from the headers crate, such as ulo_http::headers::UserAgent | no |
HeaderMap | all the request headers | no |
LastEventId | the Last-Event-ID header an SSE client sends on reconnect; see Streaming | no |
HttpCx | the call's context: head, method, URI, route, client address | no |
Host<T> | a value a middleware put in the request | no |
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.
| Variant | Meaning | HTTP |
|---|---|---|
Missing | a required header, query field, path segment, or a body that is empty | 400 |
Malformed | could not be decoded: wrong syntax, or cut off | 400 |
Mismatched | decoded, and does not fit the type | 422 |
UnsupportedMediaType | wrong Content-Type | 415, with Accept naming the media type expected |
TooLarge | over the body limit (max_body) | 413 |
Invalid | validation rules failed; see Validation | 422 |
BodyTaken | a guard or interceptor took the body first | 500, message withheld |
HostMissing | no value for Host<T>; a deployment fault | 500, message withheld |
Overflowed | a streamed body's unread items passed the transport's bound | 503 |
OverflowedBytes | a streamed body's unread items passed the transport's byte bound | 503 |
What examples/15-http-requests/tests/requests.rs asserts:
{not jsonis a 400 whosedetailstarts with"`body` could not be decoded", andtext/plainis a 415 withaccept: application/json.GET /notes/sevenfor aPath<u32>is a 400, and the handler never runs.GET /notes?limit=lotsis a 400, andGET /agentwith nouser-agentis a 400 withdetail"`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 compileThe 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.