fix(server): serve Content-Type headers with static files

This commit is contained in:
Jef Roosens 2025-06-17 15:02:46 +02:00
parent 32a4a88548
commit dd418c872a
Signed by: Jef Roosens
GPG key ID: 21FD3D77D56BAF49
4 changed files with 24 additions and 13 deletions

View file

@ -1,6 +1,6 @@
use std::io::Cursor;
use axum::{Router, routing::get};
use axum::{Router, http::header, response::IntoResponse, routing::get};
use axum_extra::{TypedHeader, headers::Range};
use axum_range::{KnownSize, Ranged};
@ -9,8 +9,6 @@ use super::Context;
const HTMX: &str = include_str!("./htmx_2.0.4.min.js");
const PICOCSS: &str = include_str!("./pico_2.1.1.classless.jade.min.css");
type RangedResponse = Ranged<KnownSize<Cursor<&'static str>>>;
pub fn router() -> Router<Context> {
Router::new()
.route("/htmx_2.0.4.min.js", get(get_htmx))
@ -18,17 +16,24 @@ pub fn router() -> Router<Context> {
}
#[inline(always)]
fn serve_static(data: &'static str, range: Option<Range>) -> RangedResponse {
fn serve_static(data: &'static str, range: Option<Range>, content_type: &str) -> impl IntoResponse {
let cursor = Cursor::new(data);
let body = KnownSize::sized(cursor, data.len() as u64);
Ranged::new(range, body)
(
[(header::CONTENT_TYPE, content_type)],
Ranged::new(range, body),
)
}
async fn get_htmx(range: Option<TypedHeader<Range>>) -> RangedResponse {
serve_static(HTMX, range.map(|TypedHeader(range)| range))
async fn get_htmx(range: Option<TypedHeader<Range>>) -> impl IntoResponse {
serve_static(
HTMX,
range.map(|TypedHeader(range)| range),
"text/javascript",
)
}
async fn get_picocss(range: Option<TypedHeader<Range>>) -> RangedResponse {
serve_static(PICOCSS, range.map(|TypedHeader(range)| range))
async fn get_picocss(range: Option<TypedHeader<Range>>) -> impl IntoResponse {
serve_static(PICOCSS, range.map(|TypedHeader(range)| range), "text/css")
}