Skip to main content

rocket_include_handlebars/debug/
handlebars_response.rs

1use std::io::Cursor;
2
3use rocket::{
4    http::Status,
5    request::Request,
6    response::{self, Responder, Response},
7};
8
9use crate::{EntityTag, EtagIfNoneMatch};
10
11#[derive(Debug)]
12enum HandlebarsResponseInner {
13    Html { content: String, etag: EntityTag<'static> },
14    NotModified(Option<String>),
15}
16
17#[derive(Debug)]
18/// To respond HTML.
19pub struct HandlebarsResponse {
20    inner: HandlebarsResponseInner,
21}
22
23impl HandlebarsResponse {
24    #[inline]
25    pub(crate) fn build_not_cache<S: Into<String>>(
26        content: S,
27        etag: EntityTag<'static>,
28    ) -> HandlebarsResponse {
29        HandlebarsResponse {
30            inner: HandlebarsResponseInner::Html {
31                content: content.into(),
32                etag,
33            },
34        }
35    }
36
37    #[doc(hidden)]
38    #[inline]
39    pub const fn not_modified() -> HandlebarsResponse {
40        HandlebarsResponse {
41            inner: HandlebarsResponseInner::NotModified(None)
42        }
43    }
44
45    #[inline]
46    pub(crate) fn not_modified_with_etag(etag: &EntityTag<'_>) -> Self {
47        Self {
48            inner: HandlebarsResponseInner::NotModified(Some(etag.to_string()))
49        }
50    }
51
52    #[doc(hidden)]
53    #[inline]
54    pub fn check_etag(self, etag_if_none_match: &EtagIfNoneMatch<'_>) -> Self {
55        match &self.inner {
56            HandlebarsResponseInner::Html {
57                etag, ..
58            } if etag_if_none_match.weak_eq(etag) => Self::not_modified_with_etag(etag),
59            _ => self,
60        }
61    }
62
63    #[doc(hidden)]
64    #[inline]
65    pub fn weak_eq(&self, etag_if_none_match: &EtagIfNoneMatch<'_>) -> bool {
66        matches!(&self.inner, HandlebarsResponseInner::Html { etag, .. } if etag_if_none_match.weak_eq(etag))
67    }
68}
69
70impl<'r, 'o: 'r> Responder<'r, 'o> for HandlebarsResponse {
71    #[inline]
72    fn respond_to(self, _: &'r Request<'_>) -> response::Result<'o> {
73        let mut response = Response::build();
74
75        match self.inner {
76            HandlebarsResponseInner::Html {
77                content,
78                etag,
79            } => {
80                response.raw_header("Content-Type", "text/html; charset=utf-8");
81                response.raw_header(EntityTag::HEADER_NAME, etag.to_string());
82                response.sized_body(content.len(), Cursor::new(content));
83            },
84            HandlebarsResponseInner::NotModified(etag) => {
85                response.status(Status::NotModified);
86
87                if let Some(etag) = etag {
88                    response.raw_header(EntityTag::HEADER_NAME, etag);
89                }
90            },
91        }
92
93        response.ok()
94    }
95}