Skip to main content

vite_static_actix_web/
lib.rs

1#![warn(clippy::pedantic)]
2
3use std::rc::Rc;
4use vite_static_shared::DynManifest;
5
6use actix_web::http::header::{CacheControl, CacheDirective};
7
8#[allow(unused_imports)]
9use vite_static_shared::Manifest;
10
11mod service;
12pub use service::*;
13
14/// Actix service for serving Vite Static.
15///
16/// This service uses [`Manifest::base()`] as root path.
17///
18/// ```no_run
19/// # use actix_web::{
20/// #     App, HttpServer,
21/// #     http::header::{CacheControl, CacheDirective},
22/// # };
23/// # use vite_static_actix_web::*;
24/// # use vite_static_shared::__tests::*;
25/// #
26/// # #[actix_web::main]
27/// # async fn main() -> std::io::Result<()> {
28/// HttpServer::new(|| {
29///     App::new()
30///         .service(ActixFiles::new(MyViteStatic.boxed()))
31/// })
32/// .bind(("127.0.0.1", 8080))?
33/// .run()
34/// .await
35/// # }
36/// ```
37#[derive(Clone)]
38pub struct ActixFiles {
39    manifest: Rc<DynManifest<'static>>,
40    cache_control: CacheControl,
41}
42
43impl ActixFiles {
44    /// Creates new [`ActixFiles`] service.
45    ///
46    /// Takes [`DynManifest`] (boxed [`Manifest`]).
47    ///
48    /// ```
49    /// # use vite_static_actix_web::*;
50    /// # use vite_static_shared::__tests::*;
51    /// #
52    /// ActixFiles::new(MyViteStatic.boxed())
53    /// # ;
54    /// ```
55    #[must_use]
56    pub fn new(manifest: DynManifest<'static>) -> Self {
57        Self {
58            manifest: Rc::new(manifest),
59            cache_control: CacheControl(vec![CacheDirective::MaxAge(604_800)]),
60        }
61    }
62
63    /// Sets [`CacheControl`] for served static.
64    ///
65    /// By default, `CacheControl` is set to "Max Age of 7 days".
66    ///
67    /// ```rust
68    /// # use actix_web::http::header::{CacheControl, CacheDirective};
69    /// # use vite_static_actix_web::*;
70    /// # use vite_static_shared::__tests::*;
71    /// #
72    /// ActixFiles::new(MyViteStatic.boxed())
73    ///     .cache_control(CacheControl(vec![CacheDirective::MaxAge(604_800)])) // 7 days
74    /// # ;
75    /// ```
76    #[must_use]
77    pub fn cache_control(mut self, value: CacheControl) -> Self {
78        self.cache_control = value;
79        self
80    }
81}