How to fetch response body from tower::util::MapResponseLayer ? #208
-
I try to return a friendly page when file examples/404.rs:
|
Beta Was this translation helpful? Give feedback.
Answered by
davidpdrsn
Aug 19, 2021
Replies: 1 comment
-
You should be able to use Something like this: use axum::{
body::{box_body, Body, BoxBody},
handler::get,
http::{Response, StatusCode},
route,
routing::RoutingDsl,
};
use std::net::SocketAddr;
#[tokio::main]
async fn main() {
let app = route("/", get(|| async {}))
// make sure this is added as the very last thing
.layer(tower::util::AndThenLayer::new(map_404));
// run it
let addr = SocketAddr::from(([127, 0, 0, 1], 3000));
axum::Server::bind(&addr)
.serve(app.into_make_service())
.await
.unwrap();
}
async fn map_404(
response: Response<BoxBody>,
) -> Result<Response<BoxBody>, std::convert::Infallible> {
if response.status() == StatusCode::NOT_FOUND
|| response.status() == StatusCode::METHOD_NOT_ALLOWED
{
return Ok(Response::builder()
.status(StatusCode::NOT_FOUND)
.body(box_body(Body::from("nothing to see here")))
.unwrap());
}
Ok(response)
} |
Beta Was this translation helpful? Give feedback.
0 replies
Answer selected by
davidpdrsn
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You should be able to use
AndThenLayer
from tower. Its basically an asyncmap_response
that can return a result as well.Something like this: