Skip to main content

blit_webserver/
lib.rs

1use axum::http::header;
2use axum::response::{Html, IntoResponse, Response};
3
4/// Serve the monospace font family list as JSON.
5pub fn fonts_list_response(cors_origin: Option<&str>) -> Response {
6    let families = blit_fonts::list_monospace_font_families();
7    let json = format!(
8        "[{}]",
9        families
10            .iter()
11            .map(|f| format!("\"{}\"", f.replace('"', "\\\"")))
12            .collect::<Vec<_>>()
13            .join(",")
14    );
15    let mut resp = (
16        [
17            (header::CONTENT_TYPE, "application/json"),
18            (header::CACHE_CONTROL, "public, max-age=3600"),
19        ],
20        json,
21    )
22        .into_response();
23    add_cors(&mut resp, cors_origin);
24    resp
25}
26
27/// Serve a font's @font-face CSS by family name, or 404.
28pub fn font_response(name: &str, cors_origin: Option<&str>) -> Response {
29    match blit_fonts::font_face_css(name) {
30        Some(css) => {
31            let mut resp = (
32                [
33                    (header::CONTENT_TYPE, "text/css"),
34                    (header::CACHE_CONTROL, "public, max-age=86400, immutable"),
35                ],
36                css,
37            )
38                .into_response();
39            add_cors(&mut resp, cors_origin);
40            resp
41        }
42        None => (axum::http::StatusCode::NOT_FOUND, "font not found").into_response(),
43    }
44}
45
46fn add_cors(resp: &mut Response, origin: Option<&str>) {
47    if let Some(origin) = origin {
48        if let Ok(val) = origin.parse() {
49            resp.headers_mut()
50                .insert(header::ACCESS_CONTROL_ALLOW_ORIGIN, val);
51        }
52    }
53}
54
55/// Serve HTML with ETag support. Returns 304 if the client's `If-None-Match`
56/// matches `etag`.
57pub fn html_response(html: &'static str, etag: &str, if_none_match: Option<&[u8]>) -> Response {
58    if let Some(inm) = if_none_match {
59        if inm == etag.as_bytes() {
60            return (
61                axum::http::StatusCode::NOT_MODIFIED,
62                [(axum::http::header::ETAG, etag)],
63            )
64                .into_response();
65        }
66    }
67    ([(axum::http::header::ETAG, etag)], Html(html)).into_response()
68}
69
70/// Try to match a font route from a raw request path (any prefix).
71/// Handles `/fonts`, `/vt/fonts`, `/font/Name`, `/vt/font/Name%20With%20Spaces`.
72/// Returns `Some(response)` if the path matched a font route, `None` otherwise.
73pub fn try_font_route(path: &str, cors_origin: Option<&str>) -> Option<Response> {
74    if path == "/fonts" || path.ends_with("/fonts") {
75        return Some(fonts_list_response(cors_origin));
76    }
77    if let Some(raw) = path.rsplit_once("/font/").map(|(_, n)| n) {
78        if !raw.contains('/') && !raw.is_empty() {
79            let name = percent_encoding::percent_decode_str(raw).decode_utf8_lossy();
80            return Some(font_response(&name, cors_origin));
81        }
82    }
83    None
84}
85
86/// Compute an ETag string from HTML content.
87pub fn html_etag(html: &str) -> String {
88    use std::hash::{Hash, Hasher};
89    let mut h = std::collections::hash_map::DefaultHasher::new();
90    html.hash(&mut h);
91    format!("\"blit-{:x}\"", h.finish())
92}