http_wasm_guest/host/body.rs
1use crate::host::{Bytes, handler};
2
3/// Handle for accessing and mutating an HTTP body stream.
4///
5/// A `Body` is tied to a specific request or response context, depending on how
6/// it is constructed. Use it to read the full buffered body or write a new one.
7pub struct Body(i32);
8
9impl Body {
10 /// Create a new body handle for the given kind.
11 pub(crate) fn new(kind: i32) -> Self {
12 Self(kind)
13 }
14
15 /// Read the entire body into memory and return it as [`Bytes`].
16 ///
17 /// This returns the buffered payload when body buffering is enabled by the host.
18 ///
19 /// `feature::BufferRequest` is required to read without consuming the request body.
20 /// To enable it, call `admin::enable(BufferRequest)` before returning from handle_request.
21 /// Otherwise, the next handler may panic attempting to read the request body because it was already read.
22 ///
23 /// `feature::BufferResponse` is required to read the response body produced by the next handler defined
24 /// on the host inside handle_response. To enable it, call `admin::enable(BufferResponse)` beforehand.
25 /// Otherwise, the guest may read EOF because the downstream handler already consumed it.
26 pub fn read(&self) -> Bytes {
27 Bytes::from(handler::body(self.0))
28 }
29
30 /// Replace the body with the provided bytes.
31 ///
32 /// Use this to set a new payload after inspecting or transforming the original.
33 pub fn write(&self, body: &[u8]) {
34 handler::write_body(self.0, body);
35 }
36}
37
38#[cfg(test)]
39mod tests {
40 use super::*;
41
42 #[test]
43 fn body_read_request() {
44 let body = Body::new(1);
45 let content = body.read();
46 // Mock returns HTML content
47 assert!(!content.is_empty());
48 assert!(content.to_str().unwrap().contains("html"));
49 }
50
51 #[test]
52 fn body_read_response() {
53 let body = Body::new(0);
54 let content = body.read();
55 assert!(content.is_empty());
56 }
57}