Responses
What an HTTP handler may return, and what each value becomes on the wire.
A handler returns (), a value, a stream, or any of those inside a Result. The Ok side must implement IntoReply<Http>; the Err side goes to the error handlers. The examples are examples/15-http-requests and examples/18-http-streaming.
| Return | Answer |
|---|---|
Json<T> | 200, application/json; T: Serialize |
String, &'static str | 200, text/plain; charset=utf-8 |
Bytes | 200, application/octet-stream |
(), NoContent | 204 |
Created<T> | 201 with a Location header and the body of T |
(StatusCode, T) | T's answer with that status |
WithHeaders<T> | T's answer with headers added |
Body | 200 with that body and no Content-Type; Body::stream(s) for a streaming one |
Sse<S> | a text/event-stream response; see Streaming and SSE |
Response | the response as built, from Response::builder() for any status, headers and body |
use ulo_http::{Created, Json, Query, Valid, WithHeaders};
#[ulo_http::post("/notes")]
fn create(&self, Valid(Json(new)): Valid<Json<NewNote>>) -> Created<Json<Note>> {
let note = self.notes.add(new.title);
Created::at(format!("/notes/{}", note.id), Json(note))
}
#[ulo_http::get("/notes")]
fn list(&self, Query(page): Query<Page>) -> WithHeaders<Json<Vec<Note>>> {
let all = self.notes.all.lock().unwrap();
let shown = all.iter().take(page.limit.unwrap_or(usize::MAX)).cloned().collect();
WithHeaders::new(Json(shown)).header("x-total-count", all.len().to_string())
}NewNote, Page and Note are the example's own types. POST /notes answers 201 with Location: /notes/1. GET /notes?limit=2 carries x-total-count beside the two notes. A Location or header value that does not parse as a header fails the reply as an IntoReplyError, which is classified Internal.
Fallible handlers
A handler returns Result<V, E> with E a classified domain error, a CallError or any Into<BoxError>. The return type may be spelled as an alias:
pub type Found = Result<Json<Note>, NoteNotFound>;An alias takes the same path as the plain Result, because the generated code looks at the type and ignores its spelling. The error is rendered by the rules in Error Handling.
Handler forms
A handler is a method with &self or self: Arc<Self>, sync or async. Both forms are covered in crates/ulo-http/tests/handlers.rs. A handler with a type or const parameter of its own is refused at compile time.