crux_http/testing/
response_builder.rs

1use http_types::headers::{HeaderName, ToHeaderValues};
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() -> ResponseBuilder<Vec<u8>> {
16        ResponseBuilder::with_status(http_types::StatusCode::Ok)
17    }
18
19    /// Constructs a new `ResponseBuilder` with the specified status code.
20    #[must_use]
21    pub fn with_status(status: http_types::StatusCode) -> ResponseBuilder<Vec<u8>> {
22        let response = Response::new_with_status(status);
23
24        ResponseBuilder { response }
25    }
26}
27
28impl<Body> ResponseBuilder<Body> {
29    /// Sets the body of the Response
30    pub fn body<NewBody>(self, body: NewBody) -> ResponseBuilder<NewBody> {
31        let response = self.response.with_body(body);
32        ResponseBuilder { response }
33    }
34
35    /// Sets a header on the response.
36    #[must_use]
37    pub fn header(mut self, key: impl Into<HeaderName>, value: impl ToHeaderValues) -> Self {
38        self.response.insert_header(key, value);
39        self
40    }
41
42    /// Builds the response
43    pub fn build(self) -> Response<Body> {
44        self.response
45    }
46}