rocket_include_static_resources/debug/
static_response.rs

1use std::sync::Arc;
2
3use mime::Mime;
4use rc_u8_reader::ArcU8Reader;
5
6use crate::{
7    rocket::{
8        http::Status,
9        request::Request,
10        response::{self, Responder, Response},
11    },
12    EntityTag,
13};
14
15#[derive(Debug)]
16struct StaticResponseInner {
17    mime: String,
18    data: Arc<Vec<u8>>,
19    etag: String,
20}
21
22#[derive(Debug)]
23/// To respond a static resource.
24pub struct StaticResponse {
25    inner: Option<StaticResponseInner>,
26}
27
28impl StaticResponse {
29    #[inline]
30    pub(crate) fn build(
31        mime: &Mime,
32        data: Arc<Vec<u8>>,
33        etag: &EntityTag<'static>,
34    ) -> StaticResponse {
35        StaticResponse {
36            inner: Some(StaticResponseInner {
37                mime: mime.to_string(),
38                data,
39                etag: etag.to_string(),
40            }),
41        }
42    }
43
44    #[inline]
45    pub(crate) const fn not_modified() -> StaticResponse {
46        StaticResponse {
47            inner: None
48        }
49    }
50}
51
52impl<'r, 'o: 'r> Responder<'r, 'o> for StaticResponse {
53    #[inline]
54    fn respond_to(self, _: &'r Request<'_>) -> response::Result<'o> {
55        let mut response = Response::build();
56
57        if let Some(inner) = self.inner {
58            response.raw_header("Etag", inner.etag);
59            response.raw_header("Content-Type", inner.mime);
60
61            response.sized_body(inner.data.len(), ArcU8Reader::new(inner.data));
62        } else {
63            response.status(Status::NotModified);
64        }
65
66        response.ok()
67    }
68}