rama_http/service/web/endpoint/extract/body/
mod.rs

1use super::FromRequest;
2use rama_http_types as http;
3use rama_utils::macros::impl_deref;
4use std::convert::Infallible;
5
6mod bytes;
7#[doc(inline)]
8pub use bytes::*;
9
10mod text;
11#[doc(inline)]
12pub use text::*;
13
14mod json;
15#[doc(inline)]
16pub use json::*;
17
18mod form;
19#[doc(inline)]
20pub use form::*;
21
22/// Extractor to get the response body.
23#[derive(Debug)]
24pub struct Body(pub http::Body);
25
26impl_deref!(Body: http::Body);
27
28impl FromRequest for Body {
29    type Rejection = Infallible;
30
31    async fn from_request(req: http::Request) -> Result<Self, Self::Rejection> {
32        Ok(Self(req.into_body()))
33    }
34}
35
36#[cfg(test)]
37mod test {
38    use super::*;
39    use crate::dep::http_body_util::BodyExt;
40    use crate::service::web::WebService;
41    use crate::{Method, Request, StatusCode};
42    use rama_core::{Context, Service};
43
44    #[tokio::test]
45    async fn test_body() {
46        let service = WebService::default().get("/", |Body(body): Body| async move {
47            let body = body.collect().await.unwrap().to_bytes();
48            assert_eq!(body, "test");
49        });
50
51        let req = Request::builder()
52            .method(Method::GET)
53            .body("test".into())
54            .unwrap();
55        let resp = service.serve(Context::default(), req).await.unwrap();
56        assert_eq!(resp.status(), StatusCode::OK);
57    }
58}