assets.rs

 1use crate::{AppState, Request};
 2use anyhow::anyhow;
 3use rust_embed::RustEmbed;
 4use std::sync::Arc;
 5use tide::{http::mime, Server};
 6
 7#[derive(RustEmbed)]
 8#[folder = "static"]
 9struct Static;
10
11pub fn add_routes(app: &mut Server<Arc<AppState>>) {
12    app.at("/static/*path").get(get_static_asset);
13}
14
15async fn get_static_asset(request: Request) -> tide::Result {
16    let path = request.param("path").unwrap();
17    let content = Static::get(path).ok_or_else(|| anyhow!("asset not found at {}", path))?;
18
19    let content_type = if path.starts_with("svg") {
20        mime::SVG
21    } else if path.starts_with("styles") {
22        mime::CSS
23    } else {
24        mime::BYTE_STREAM
25    };
26
27    Ok(tide::Response::builder(200)
28        .content_type(content_type)
29        .body(content.data.as_ref())
30        .build())
31}