http-request 21.7.7

http-request is a lightweight, efficient library for building, sending, and handling HTTP/HTTPS requests in Rust applications. It provides a simple and intuitive API, allowing developers to easily interact with web services, whether they use the "HTTP" or "HTTPS" protocol. The library supports various HTTP methods, custom headers, request bodies, timeout, automatic handling of redirects (including detecting redirect loops), and enhanced response body decoding (both automatic and manual), enabling fast and secure communication. Whether working with secure "HTTPS" connections or standard "HTTP" requests, the library is optimized for performance, minimal resource usage, and easy integration into Rust projects.
Documentation
use super::*;

/// HTTP request body content.
///
/// Holds the raw bytes of the request body. Use [`RequestBuilder::body`] /
/// [`RequestBuilder::body_json`] / [`RequestBuilder::body_text`] on the builder
/// to populate; users normally do not construct `Body` directly.
///
/// `Body` is intentionally a single-value type (`Vec<u8>`) to match the
/// `Request` / `Response` design in `hyperlane-core` — see
/// `hyperlane-standards §8.1`. Higher-level framing (json vs text vs binary)
/// lives in the builder, not in the data type.
#[derive(Clone, Debug, Default, Eq, Getter, PartialEq, Serialize)]
pub struct Body {
    /// Raw body bytes.
    pub bytes: Vec<u8>,
}

impl Body {
    /// Empty body.
    pub const fn empty() -> Self {
        Self { bytes: Vec::new() }
    }

    /// Construct from any `Into<Vec<u8>>`.
    pub fn from_bytes<B: Into<Vec<u8>>>(bytes: B) -> Self {
        Self {
            bytes: bytes.into(),
        }
    }

    /// View body as `&[u8]`.
    ///
    /// # Returns
    ///
    /// - `&[u8]` - The raw body bytes.
    pub fn get_bytes_ref(&self) -> &[u8] {
        &self.bytes
    }

    /// View body as `&[u8]`.
    pub fn as_slice(&self) -> &[u8] {
        self.get_bytes()
    }

    /// Try to view body as UTF-8 string.
    pub fn as_str(&self) -> Option<&str> {
        std::str::from_utf8(self.get_bytes()).ok()
    }
}

impl Display for Body {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        match self.as_str() {
            Some(s) => f.write_str(s),
            None => f.write_str(&format!("{:?}", self.bytes)),
        }
    }
}