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)]
12struct HandlebarsResponseInner {
13    content: String,
14    etag:    String,
15}
16
17#[derive(Debug)]
18/// To respond HTML.
19pub struct HandlebarsResponse {
20    inner: Option<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: Some(HandlebarsResponseInner {
31                content: content.into(),
32                etag:    etag.to_string(),
33            }),
34        }
35    }
36
37    #[doc(hidden)]
38    #[inline]
39    pub const fn not_modified() -> HandlebarsResponse {
40        HandlebarsResponse {
41            inner: None
42        }
43    }
44
45    #[doc(hidden)]
46    #[inline]
47    pub fn weak_eq(&self, etag_if_none_match: &EtagIfNoneMatch<'_>) -> bool {
48        self.inner
49            .as_ref()
50            .map(|inner| {
51                etag_if_none_match.weak_eq(unsafe {
52                    &EntityTag::with_str_unchecked(false, &inner.etag[1..(inner.etag.len() - 1)])
53                })
54            })
55            .unwrap_or(false)
56    }
57}
58
59impl<'r, 'o: 'r> Responder<'r, 'o> for HandlebarsResponse {
60    #[inline]
61    fn respond_to(self, _: &'r Request<'_>) -> response::Result<'o> {
62        let mut response = Response::build();
63
64        if let Some(inner) = self.inner {
65            response.raw_header("Content-Type", "text/html; charset=utf-8");
66            response.raw_header("Etag", inner.etag);
67
68            response.sized_body(inner.content.len(), Cursor::new(inner.content));
69        } else {
70            response.status(Status::NotModified);
71        }
72
73        response.ok()
74    }
75}