summaryrefslogtreecommitdiff
path: root/src/ui.rs
blob: 18dd04965e4227d065f1a48fdefbdfef7fb0748b (plain)
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
48
49
50
51
52
53
54
55
56
57
58
59
60
use axum::{
    extract::Path,
    http::{header, StatusCode},
    response::{IntoResponse, Response},
    routing::get,
    Router,
};
use mime_guess::Mime;
use rust_embed::EmbeddedFile;

#[derive(rust_embed::Embed)]
#[folder = "hi-ui/build"]
struct Assets;

pub fn router<S>() -> Router<S>
where
    S: Clone + Send + Sync + 'static,
{
    Router::new()
        .route("/*path", get(asset))
        .route("/", get(root))
}

async fn asset(Path(path): Path<String>) -> Result<Asset, NotFound<String>> {
    let mime = mime_guess::from_path(&path).first_or_octet_stream();

    Assets::get(&path)
        .map(|file| Asset(mime, file))
        .ok_or(NotFound(format!("not found: {path}")))
}

async fn root() -> impl IntoResponse {
    asset(Path(String::from("index.html"))).await
}

struct Asset(Mime, EmbeddedFile);

impl IntoResponse for Asset {
    fn into_response(self) -> Response {
        let Self(mime, file) = self;
        (
            StatusCode::OK,
            [(header::CONTENT_TYPE, mime.as_ref())],
            file.data,
        )
            .into_response()
    }
}

struct NotFound<E>(pub E);

impl<E> IntoResponse for NotFound<E>
where
    E: IntoResponse,
{
    fn into_response(self) -> Response {
        let Self(response) = self;
        (StatusCode::NOT_FOUND, response).into_response()
    }
}