rocket_include_static_resources/debug/
fairing.rs

1use std::sync::{Mutex, MutexGuard, PoisonError};
2
3use super::{FileResources, StaticContextManager, StaticResponse};
4use crate::rocket::{
5    fairing::{Fairing, Info, Kind},
6    Build, Rocket,
7};
8
9const FAIRING_NAME: &str = "Static Resources (Debug)";
10
11/// The fairing of `StaticResponse`.
12pub struct StaticResponseFairing {
13    #[allow(clippy::type_complexity)]
14    pub(crate) custom_callback: Box<dyn Fn(&mut MutexGuard<FileResources>) + Send + Sync + 'static>,
15}
16
17#[rocket::async_trait]
18impl Fairing for StaticResponseFairing {
19    #[inline]
20    fn info(&self) -> Info {
21        Info {
22            name: FAIRING_NAME, kind: Kind::Ignite
23        }
24    }
25
26    #[inline]
27    async fn on_ignite(&self, rocket: Rocket<Build>) -> Result<Rocket<Build>, Rocket<Build>> {
28        let resources = Mutex::new(FileResources::new());
29
30        (self.custom_callback)(&mut resources.lock().unwrap_or_else(PoisonError::into_inner));
31
32        let state = StaticContextManager::new(resources);
33
34        Ok(rocket.manage(state))
35    }
36}
37
38impl StaticResponse {
39    #[inline]
40    /// Create the fairing of `HandlebarsResponse`.
41    pub fn fairing<F>(f: F) -> impl Fairing
42    where
43        F: Fn(&mut MutexGuard<FileResources>) + Send + Sync + 'static, {
44        StaticResponseFairing {
45            custom_callback: Box::new(f)
46        }
47    }
48}