Generic request body (#22)

Fixes #21
This commit is contained in:
David Pedersen
2021-06-19 12:50:33 +02:00
committed by GitHub
parent 6a16cd40ca
commit 356f1c8424
20 changed files with 692 additions and 401 deletions
+48 -2
View File
@@ -8,7 +8,7 @@ use std::{
net::{SocketAddr, TcpListener},
time::Duration,
};
use tower::{make::Shared, BoxError, Service, ServiceBuilder};
use tower::{make::Shared, service_fn, BoxError, Service, ServiceBuilder};
use tower_http::{compression::CompressionLayer, trace::TraceLayer};
#[tokio::test]
@@ -329,7 +329,6 @@ async fn boxing() {
#[tokio::test]
async fn service_handlers() {
use crate::service::ServiceExt as _;
use tower::service_fn;
use tower_http::services::ServeFile;
let app = route(
@@ -607,6 +606,53 @@ async fn typed_header() {
assert_eq!(body, "invalid HTTP header (user-agent)");
}
#[tokio::test]
async fn different_request_body_types() {
use http_body::{Empty, Full};
use std::convert::Infallible;
use tower_http::map_request_body::MapRequestBodyLayer;
async fn handler(body: String) -> String {
body
}
async fn svc_handler<B>(req: Request<B>) -> Result<Response<Body>, Infallible>
where
B: http_body::Body,
B::Error: std::fmt::Debug,
{
let body = hyper::body::to_bytes(req.into_body()).await.unwrap();
Ok(Response::new(Body::from(body)))
}
let app = route("/", service::get(service_fn(svc_handler)))
.route(
"/foo",
get(handler.layer(MapRequestBodyLayer::new(|_| Full::<Bytes>::from("foo")))),
)
.layer(MapRequestBodyLayer::new(|_| Empty::<Bytes>::new()));
let addr = run_in_background(app).await;
let client = reqwest::Client::new();
let res = client
.get(format!("http://{}/", addr))
.send()
.await
.unwrap();
let body = res.text().await.unwrap();
assert_eq!(body, "");
let res = client
.get(format!("http://{}/foo", addr))
.send()
.await
.unwrap();
let body = res.text().await.unwrap();
assert_eq!(body, "foo");
}
/// Run a `tower::Service` in the background and get a URI for it.
async fn run_in_background<S, ResBody>(svc: S) -> SocketAddr
where