Skip to main content

http_wasm_guest/host/
response.rs

1use crate::host::{Body, Header, handler};
2/// Handle for accessing and mutating the current HTTP response.
3pub struct Response {
4    /// Handle for accessing and mutating response headers.
5    pub header: Header,
6    /// Handle for reading or writing the response body.
7    pub body: Body,
8}
9const KIND_RES: i32 = 1;
10
11impl Response {
12    /// Creates a new `Response` instance with header and body handles.
13    pub(crate) fn new() -> Self {
14        Self { header: Header::new(KIND_RES), body: Body::new(KIND_RES) }
15    }
16    /// Return the current response status code.
17    pub fn status(&self) -> i32 {
18        handler::status_code()
19    }
20
21    /// Set the response status code.
22    ///
23    /// To call this in `handle_response` requires `feature::BufferResponse`.
24    pub fn set_status(&self, code: i32) {
25        handler::set_status_code(code);
26    }
27
28    /// Return a handle for accessing and mutating response headers.
29    #[deprecated(since = "0.11.2", note = "use the `header` field directly instead")]
30    pub fn header(&self) -> &Header {
31        &self.header
32    }
33
34    /// Return a handle for reading or writing the response body.
35    #[deprecated(since = "0.11.2", note = "use the `body` field directly instead")]
36    pub fn body(&self) -> &Body {
37        &self.body
38    }
39}
40
41#[cfg(test)]
42mod tests {
43    use super::*;
44
45    #[test]
46    fn test_body() {
47        let r = Response::new();
48        let sut = r.body.read();
49        assert!(!sut.is_empty());
50        assert!(sut.starts_with(b"<html>"));
51    }
52
53    #[test]
54    fn response_status() {
55        let response = Response::new();
56        // The mock returns 200
57        assert_eq!(response.status(), 200);
58    }
59
60    #[test]
61    fn response_set_status() {
62        let response = Response::new();
63        // Should not panic - mock accepts any status
64        response.set_status(404);
65    }
66
67    #[test]
68    fn response_header_access() {
69        let response = Response::new();
70        let header = response.header;
71        // Response headers use kind=1, should still work
72        let _ = header.names_iter();
73    }
74
75    #[test]
76    fn response_body_read() {
77        let response = Response::new();
78        let body = response.body;
79        let content = body.read();
80        // The mock returns HTML content
81        assert!(!content.is_empty());
82    }
83
84    #[test]
85    fn response_body_write() {
86        let response = Response::new();
87        let body = response.body;
88        // Should not panic - mock accepts any body
89        body.write(b"<html><body>Custom Response</body></html>");
90    }
91}