Skip to main content

crux_http/testing/
response_builder.rs

1use http::{HeaderValue, StatusCode};
2
3use crate::response::Response;
4
5/// Allows users to build an http response.
6///
7/// This is mostly expected to be useful in tests rather than application code.
8pub struct ResponseBuilder<Body> {
9    response: Response<Body>,
10}
11
12impl ResponseBuilder<Vec<u8>> {
13    /// Constructs a new `ResponseBuilder` with the 200 OK status code.
14    #[must_use]
15    pub fn ok() -> Self {
16        Self::with_status(200)
17    }
18
19    /// Constructs a new `ResponseBuilder` with the specified status code.
20    ///
21    /// # Panics
22    ///
23    /// Panics if `status` is outside the valid HTTP range (100–999).
24    #[must_use]
25    pub fn with_status(status: u16) -> Self {
26        let status = StatusCode::from_u16(status).expect(
27            "ResponseBuilder::with_status called with an out-of-range code (must be 100–999)",
28        );
29        let response = Response::new_with_status(status);
30        Self { response }
31    }
32}
33
34impl<Body> ResponseBuilder<Body> {
35    /// Sets the body of the Response.
36    pub fn body<NewBody>(self, body: NewBody) -> ResponseBuilder<NewBody> {
37        let response = self.response.with_body(body);
38        ResponseBuilder { response }
39    }
40
41    /// Sets a header on the response, replacing any existing value for that name.
42    ///
43    /// # Panics
44    /// Panics if `value` is not a valid header value.
45    #[must_use]
46    pub fn header(
47        mut self,
48        name: impl http::header::IntoHeaderName,
49        value: impl AsRef<str>,
50    ) -> Self {
51        let value = HeaderValue::from_str(value.as_ref()).expect("invalid header value");
52        self.response.insert_header(name, value);
53        self
54    }
55
56    /// Appends a header value, keeping any existing values for that name.
57    ///
58    /// Use this when building responses with multiple values for the same header
59    /// (e.g. `Set-Cookie`).
60    ///
61    /// # Panics
62    /// Panics if `value` is not a valid header value.
63    #[must_use]
64    pub fn append_header(
65        mut self,
66        name: impl http::header::IntoHeaderName,
67        value: impl AsRef<str>,
68    ) -> Self {
69        let value = HeaderValue::from_str(value.as_ref()).expect("invalid header value");
70        self.response.append_header(name, value);
71        self
72    }
73
74    /// Builds the response.
75    pub fn build(self) -> Response<Body> {
76        self.response
77    }
78}