mirror of
https://github.com/tokio-rs/axum.git
synced 2026-08-23 00:00:15 +02:00
Add middleware::from_fn for creating middleware from async fns (#656)
* Add `middleware::from_fn` for creating middleware from async fns * More trait impls for `Next` * Make `Next::run` consume `self` * Use `.router_layer` in example, since middleware returns early * Actually `Next` probably shouldn't impl `Clone` and `Service` Has implications for backpressure and stuff * Simplify `print-request-response` example * Address review feedback * add changelog link
This commit is contained in:
@@ -6,6 +6,7 @@ publish = false
|
||||
|
||||
[dependencies]
|
||||
axum = { path = "../../axum" }
|
||||
axum-extra = { path = "../../axum-extra" }
|
||||
tokio = { version = "1.0", features = ["full"] }
|
||||
tracing = "0.1"
|
||||
tracing-subscriber = { version="0.3", features = ["env-filter"] }
|
||||
|
||||
@@ -6,14 +6,13 @@
|
||||
|
||||
use axum::{
|
||||
body::{Body, Bytes},
|
||||
error_handling::HandleErrorLayer,
|
||||
http::{Request, StatusCode},
|
||||
response::Response,
|
||||
response::{IntoResponse, Response},
|
||||
routing::post,
|
||||
Router,
|
||||
};
|
||||
use axum_extra::middleware::{self, Next};
|
||||
use std::net::SocketAddr;
|
||||
use tower::{filter::AsyncFilterLayer, util::AndThenLayer, BoxError, ServiceBuilder};
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() {
|
||||
@@ -28,17 +27,7 @@ async fn main() {
|
||||
|
||||
let app = Router::new()
|
||||
.route("/", post(|| async move { "Hello from `POST /`" }))
|
||||
.layer(
|
||||
ServiceBuilder::new()
|
||||
.layer(HandleErrorLayer::new(|error| async move {
|
||||
(
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
format!("Unhandled internal error: {}", error),
|
||||
)
|
||||
}))
|
||||
.layer(AndThenLayer::new(map_response))
|
||||
.layer(AsyncFilterLayer::new(map_request)),
|
||||
);
|
||||
.layer(middleware::from_fn(print_request_response));
|
||||
|
||||
let addr = SocketAddr::from(([127, 0, 0, 1], 3000));
|
||||
tracing::debug!("listening on {}", addr);
|
||||
@@ -48,28 +37,41 @@ async fn main() {
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
async fn map_request(req: Request<Body>) -> Result<Request<Body>, BoxError> {
|
||||
async fn print_request_response(
|
||||
req: Request<Body>,
|
||||
next: Next<Body>,
|
||||
) -> Result<impl IntoResponse, (StatusCode, String)> {
|
||||
let (parts, body) = req.into_parts();
|
||||
let bytes = buffer_and_print("request", body).await?;
|
||||
let req = Request::from_parts(parts, Body::from(bytes));
|
||||
Ok(req)
|
||||
}
|
||||
|
||||
async fn map_response(res: Response) -> Result<Response<Body>, BoxError> {
|
||||
let res = next.run(req).await;
|
||||
|
||||
let (parts, body) = res.into_parts();
|
||||
let bytes = buffer_and_print("response", body).await?;
|
||||
let res = Response::from_parts(parts, Body::from(bytes));
|
||||
|
||||
Ok(res)
|
||||
}
|
||||
|
||||
async fn buffer_and_print<B>(direction: &str, body: B) -> Result<Bytes, BoxError>
|
||||
async fn buffer_and_print<B>(direction: &str, body: B) -> Result<Bytes, (StatusCode, String)>
|
||||
where
|
||||
B: axum::body::HttpBody<Data = Bytes>,
|
||||
B::Error: Into<BoxError>,
|
||||
B::Error: std::fmt::Display,
|
||||
{
|
||||
let bytes = hyper::body::to_bytes(body).await.map_err(Into::into)?;
|
||||
let bytes = match hyper::body::to_bytes(body).await {
|
||||
Ok(bytes) => bytes,
|
||||
Err(err) => {
|
||||
return Err((
|
||||
StatusCode::BAD_REQUEST,
|
||||
format!("failed to read {} body: {}", direction, err),
|
||||
));
|
||||
}
|
||||
};
|
||||
|
||||
if let Ok(body) = std::str::from_utf8(&bytes) {
|
||||
tracing::debug!("{} body = {:?}", direction, body);
|
||||
}
|
||||
|
||||
Ok(bytes)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user