Files
axum/examples/print-request-response/src/main.rs
T
David Pedersen f4716084a7 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
2021-12-27 14:01:26 +01:00

78 lines
2.0 KiB
Rust

//! Run with
//!
//! ```not_rust
//! cargo run -p example-print-request-response
//! ```
use axum::{
body::{Body, Bytes},
http::{Request, StatusCode},
response::{IntoResponse, Response},
routing::post,
Router,
};
use axum_extra::middleware::{self, Next};
use std::net::SocketAddr;
#[tokio::main]
async fn main() {
// Set the RUST_LOG, if it hasn't been explicitly defined
if std::env::var_os("RUST_LOG").is_none() {
std::env::set_var(
"RUST_LOG",
"example_print_request_response=debug,tower_http=debug",
)
}
tracing_subscriber::fmt::init();
let app = Router::new()
.route("/", post(|| async move { "Hello from `POST /`" }))
.layer(middleware::from_fn(print_request_response));
let addr = SocketAddr::from(([127, 0, 0, 1], 3000));
tracing::debug!("listening on {}", addr);
axum::Server::bind(&addr)
.serve(app.into_make_service())
.await
.unwrap();
}
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));
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, (StatusCode, String)>
where
B: axum::body::HttpBody<Data = Bytes>,
B::Error: std::fmt::Display,
{
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)
}