sailboat/
response.rs

1use std::{fs::File, io::Read, sync::mpsc::Receiver};
2
3use tiny_http::{Header, StatusCode};
4
5/// Wrapping response body intended to be returned by services.
6pub struct Response(tiny_http::ResponseBox);
7
8impl From<Response> for tiny_http::ResponseBox {
9    fn from(value: Response) -> Self {
10        value.0
11    }
12}
13
14impl Response {
15    /// General response constructor
16    pub fn new<R: Read + Send + 'static>(
17        status_code: StatusCode,
18        headers: Vec<Header>,
19        data: R,
20        data_length: Option<usize>,
21        additional_headers: Option<Receiver<Header>>,
22    ) -> Self {
23        Self(
24            tiny_http::Response::new(status_code, headers, data, data_length, additional_headers)
25                .boxed(),
26        )
27    }
28
29    /// Status code 200 with file in the body
30    pub fn file(file: File) -> Self {
31        Self(tiny_http::Response::from_file(file).boxed())
32    }
33
34    /// Empty response used to send status codes
35    pub fn empty(status_code: StatusCode) -> Self {
36        Self(tiny_http::Response::empty(status_code).boxed())
37    }
38
39    /// Insert a header to the underlying `Response` object
40    pub fn with_header(mut self, key: &str, value: &str) -> Result<Self, ()> {
41        let header = Header::from_bytes(key, value)?;
42        self.0 = self.0.with_header(header);
43
44        Ok(self)
45    }
46}