pub trait IntoResponse {
// Required method
fn into_response(self) -> Response;
}
Expand description
Trait for generating responses.
Types that implement IntoResponse
can be returned from handlers.
§Implementing IntoResponse
You generally shouldn’t have to implement IntoResponse
manually, as axum
provides implementations for many common types.
However it might be necessary if you have a custom error type that you want to return from handlers:
use axum::{
Router,
body::{self, Bytes},
routing::get,
http::StatusCode,
response::{IntoResponse, Response},
};
enum MyError {
SomethingWentWrong,
SomethingElseWentWrong,
}
impl IntoResponse for MyError {
fn into_response(self) -> Response {
let body = match self {
MyError::SomethingWentWrong => "something went wrong",
MyError::SomethingElseWentWrong => "something else went wrong",
};
// it's often easiest to implement `IntoResponse` by calling other implementations
(StatusCode::INTERNAL_SERVER_ERROR, body).into_response()
}
}
// `Result<impl IntoResponse, MyError>` can now be returned from handlers
let app = Router::new().route("/", get(handler));
async fn handler() -> Result<(), MyError> {
Err(MyError::SomethingWentWrong)
}
Or if you have a custom body type you’ll also need to implement
IntoResponse
for it:
use axum::{
body,
routing::get,
response::{IntoResponse, Response},
body::Body,
Router,
};
use http::HeaderMap;
use bytes::Bytes;
use http_body::Frame;
use std::{
convert::Infallible,
task::{Poll, Context},
pin::Pin,
};
struct MyBody;
// First implement `Body` for `MyBody`. This could for example use
// some custom streaming protocol.
impl http_body::Body for MyBody {
type Data = Bytes;
type Error = Infallible;
fn poll_frame(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
) -> Poll<Option<Result<Frame<Self::Data>, Self::Error>>> {
// ...
}
}
// Now we can implement `IntoResponse` directly for `MyBody`
impl IntoResponse for MyBody {
fn into_response(self) -> Response {
Response::new(Body::new(self))
}
}
// `MyBody` can now be returned from handlers.
let app = Router::new().route("/", get(|| async { MyBody }));
Required Methods§
sourcefn into_response(self) -> Response
fn into_response(self) -> Response
Create a response.