about summary refs log tree commit diff
path: root/templates/src/assets.rs
blob: 493c14d7fbe44f3c642c233b47ff9e11492d654c (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
use axum::extract::Path;
use axum::http::header::{CACHE_CONTROL, CONTENT_ENCODING, CONTENT_TYPE, X_CONTENT_TYPE_OPTIONS};
use axum::http::StatusCode;
use axum::response::{IntoResponse, Response};

const ASSETS: include_dir::Dir<'static> = include_dir::include_dir!("$OUT_DIR/");
const CACHE_FOR_A_DAY: &str = "max-age=86400";
const GZIP: &str = "gzip";

pub async fn statics(Path(path): Path<String>) -> Response {
    let content_type: &'static str = if path.ends_with(".js") {
        "application/javascript"
    } else if path.ends_with(".css") {
        "text/css"
    } else if path.ends_with(".html") {
        "text/html; charset=\"utf-8\""
    } else {
        "application/octet-stream"
    };

    match ASSETS.get_file(path.clone() + ".gz") {
        Some(file) => (
            StatusCode::OK,
            [
                (CONTENT_TYPE, content_type),
                (CONTENT_ENCODING, GZIP),
                (CACHE_CONTROL, CACHE_FOR_A_DAY),
                (X_CONTENT_TYPE_OPTIONS, "nosniff"),
            ],
            file.contents(),
        )
            .into_response(),
        None => match ASSETS.get_file(path) {
            Some(file) => (
                StatusCode::OK,
                [
                    (CONTENT_TYPE, content_type),
                    (CACHE_CONTROL, CACHE_FOR_A_DAY),
                    (X_CONTENT_TYPE_OPTIONS, "nosniff"),
                ],
                file.contents(),
            )
                .into_response(),
            None => StatusCode::NOT_FOUND.into_response(),
        },
    }
}