Skip to main content

ferro_rs/http/
body.rs

1//! Body parsing utilities for HTTP requests
2//!
3//! Provides async body collection and parsing for JSON and form-urlencoded data.
4
5use crate::error::FrameworkError;
6use bytes::Bytes;
7use http_body_util::BodyExt;
8use hyper::body::Incoming;
9use serde::de::DeserializeOwned;
10
11/// Collect the full body from an Incoming stream
12pub async fn collect_body(body: Incoming) -> Result<Bytes, FrameworkError> {
13    body.collect()
14        .await
15        .map(|collected| collected.to_bytes())
16        .map_err(|e| FrameworkError::internal(format!("Failed to read request body: {e}")))
17}
18
19/// Parse bytes as JSON into the target type
20pub fn parse_json<T: DeserializeOwned>(bytes: &Bytes) -> Result<T, FrameworkError> {
21    serde_json::from_slice(bytes)
22        .map_err(|e| FrameworkError::internal(format!("Failed to parse JSON body: {e}")))
23}
24
25/// Parse bytes as form-urlencoded into the target type
26pub fn parse_form<T: DeserializeOwned>(bytes: &Bytes) -> Result<T, FrameworkError> {
27    serde_urlencoded::from_bytes(bytes)
28        .map_err(|e| FrameworkError::internal(format!("Failed to parse form body: {e}")))
29}