Skip to content

Instantly share code, notes, and snippets.

@Szymongib
Last active November 19, 2024 20:45
Show Gist options
  • Save Szymongib/7d9ab3318e3c30cf231963d083d30d7d to your computer and use it in GitHub Desktop.
Save Szymongib/7d9ab3318e3c30cf231963d083d30d7d to your computer and use it in GitHub Desktop.
Plugable filter for logging request body using Warp
// warp version 0.2.2
use warp::{Filter, Rejection};
use bytes::{Bytes, Buf};
#[tokio::main]
async fn main() {
let port: u16 = 8080;
let api = warp::any()
.and(log_body())
.and_then(handle);
let server_future = warp::serve(api).run(([0, 0, 0, 0], port.clone()));
server_future.await;
}
fn log_body() -> impl Filter<Extract = (), Error = Rejection> + Copy {
warp::body::bytes()
.map(|b: Bytes| {
println!("Request body: {}", std::str::from_utf8(b.bytes()).expect("error converting bytes to &str"));
})
.untuple_one()
}
async fn handle() -> Result<impl warp::Reply, warp::Rejection> {
Ok(warp::reply::reply())
}
@bvjebin
Copy link

bvjebin commented Nov 19, 2024

This consumes the body and so it is not available for extraction in the handler.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment