mirror of
https://github.com/rm-dr/servable.git
synced 2025-11-28 05:19:33 -08:00
v0.0.3
This commit is contained in:
@@ -1,17 +1,19 @@
|
||||
# Servable: a simple web framework
|
||||
|
||||
### TODO:
|
||||
- cache-bust fonts in css (dynamic replace in css (fonts))
|
||||
|
||||
|
||||
[](https://github.com/rm-dr/servable/actions)
|
||||
[](https://crates.io/crates/servable)
|
||||
[](https://docs.rs/servable/)
|
||||
|
||||
A tiny, convenient web micro-framework built around [htmx](https://htmx.org), [Axum](https://github.com/tokio-rs/axum), and [Maud](https://maud.lambda.xyz).
|
||||
Inspired by the "MASH" stack described [here](https://yree.io/mash) and [here](https://emschwartz.me/building-a-fast-website-with-the-mash-stack-in-rust).
|
||||
|
||||
|
||||
A minimal, convenient web micro-framework built around [htmx](https://htmx.org), [Axum](https://github.com/tokio-rs/axum), and [Maud](https://maud.lambda.xyz). \
|
||||
This powers [my homepage](https://betalupi.com). See example usage [here](https://git.betalupi.com/Mark/webpage/src/branch/main/crates/service/service-webpage/src/routes/mod.rs).
|
||||
|
||||
## Features
|
||||
|
||||
`servable` provides abstractions that implement common utilities needed by an http server. \
|
||||
`servable` provides abstractions that implement common utilities needed by an http server.
|
||||
|
||||
- response headers and cache-busting utilities
|
||||
- client device detection (mobile / desktop)
|
||||
@@ -63,6 +65,7 @@ The `Servable` trait is the foundation of this stack. \
|
||||
let asset = StaticAsset {
|
||||
bytes: b"body { color: red; }",
|
||||
mime: MimeType::Css,
|
||||
ttl: StaticAsset::DEFAULT_TTL
|
||||
};
|
||||
```
|
||||
|
||||
@@ -104,10 +107,10 @@ A `ServableRouter` exposes a collection of `Servable`s under different routes. I
|
||||
|
||||
```rust
|
||||
# use servable::{ServableRouter, StaticAsset, mime::MimeType};
|
||||
# let home_page = StaticAsset { bytes: b"home", mime: MimeType::Html };
|
||||
# let about_page = StaticAsset { bytes: b"about", mime: MimeType::Html };
|
||||
# let stylesheet = StaticAsset { bytes: b"css", mime: MimeType::Css };
|
||||
# let custom_404_page = StaticAsset { bytes: b"404", mime: MimeType::Html };
|
||||
# let home_page = StaticAsset { bytes: b"home", mime: MimeType::Html, ttl: StaticAsset::DEFAULT_TTL};
|
||||
# let about_page = StaticAsset { bytes: b"about", mime: MimeType::Html, ttl: StaticAsset::DEFAULT_TTL };
|
||||
# let stylesheet = StaticAsset { bytes: b"css", mime: MimeType::Css, ttl: StaticAsset::DEFAULT_TTL };
|
||||
# let custom_404_page = StaticAsset { bytes: b"404", mime: MimeType::Html, ttl: StaticAsset::DEFAULT_TTL };
|
||||
let route = ServableRouter::new()
|
||||
.add_page("/", home_page)
|
||||
.add_page("/about", about_page)
|
||||
@@ -129,6 +132,7 @@ let route = ServableRouter::new()
|
||||
StaticAsset {
|
||||
bytes: b"fake image data",
|
||||
mime: MimeType::Png,
|
||||
ttl: StaticAsset::DEFAULT_TTL
|
||||
}
|
||||
);
|
||||
```
|
||||
@@ -139,13 +143,13 @@ let route = ServableRouter::new()
|
||||
GET /image.png
|
||||
|
||||
# Resize to max 800px on longest side
|
||||
GET /image.png?t=maxdim(800)
|
||||
GET /image.png?t=maxdim(800,800)
|
||||
|
||||
# Crop to a 400x400 square at the center of the image
|
||||
GET /image.png?t=crop(400,400,c)
|
||||
|
||||
# Chain transformations and transcode
|
||||
GET /image.png?t=maxdim(800);crop(400,400);format(webp)
|
||||
GET /image.png?t=maxdim(800,800);crop(400,400);format(webp)
|
||||
```
|
||||
|
||||
|
||||
@@ -171,9 +175,34 @@ use servable::HtmlPage;
|
||||
|
||||
let page = HtmlPage::default()
|
||||
.with_ttl(Some(TimeDelta::hours(1)))
|
||||
.with_immutable(false);
|
||||
.with_private(false);
|
||||
```
|
||||
|
||||
Headers are automatically generated:
|
||||
- `Cache-Control: public, max-age=3600`
|
||||
- `Cache-Control: immutable, public, max-age=31536000` (for immutable assets)
|
||||
- `Cache-Control: public, max-age=3600` (default)
|
||||
- `Cache-Control: private, max-age=31536000` (if `private` is true)
|
||||
|
||||
We also provide a static `CACHE_BUST_STR`, which may be formatted into urls to force cache refresh
|
||||
whenever the server is restarted:
|
||||
|
||||
```rust
|
||||
use chrono::TimeDelta;
|
||||
use servable::{HtmlPage, CACHE_BUST_STR, ServableWithRoute, StaticAsset, ServableRouter};
|
||||
use servable::mime::MimeType;
|
||||
|
||||
pub static HTMX: ServableWithRoute<StaticAsset> = ServableWithRoute::new(
|
||||
|| format!("/{}/main.css", *CACHE_BUST_STR),
|
||||
StaticAsset {
|
||||
bytes: "div{}".as_bytes(),
|
||||
mime: MimeType::Css,
|
||||
ttl: StaticAsset::DEFAULT_TTL,
|
||||
},
|
||||
);
|
||||
|
||||
|
||||
let route = HTMX.route();
|
||||
println!("Css is at {route}");
|
||||
|
||||
let router = ServableRouter::new()
|
||||
.add_page_with_route(&HTMX);
|
||||
```
|
||||
|
||||
@@ -1,4 +1,8 @@
|
||||
#![doc = include_str!("../README.md")]
|
||||
// readme is symlinked to the root of this repo
|
||||
// because `cargo publish` works from a different dir,
|
||||
// and needs a different relative path than cargo build.
|
||||
// https://github.com/rust-lang/cargo/issues/13309
|
||||
|
||||
pub mod mime;
|
||||
|
||||
@@ -44,6 +48,7 @@ pub static CACHE_BUST_STR: std::sync::LazyLock<String> = std::sync::LazyLock::ne
|
||||
pub const HTMX_2_0_8: servable::StaticAsset = servable::StaticAsset {
|
||||
bytes: include_str!("../htmx/htmx-2.0.8.min.js").as_bytes(),
|
||||
mime: mime::MimeType::Javascript,
|
||||
ttl: StaticAsset::DEFAULT_TTL,
|
||||
};
|
||||
|
||||
/// HTMX json extension, 1.19.2.
|
||||
@@ -53,4 +58,5 @@ pub const HTMX_2_0_8: servable::StaticAsset = servable::StaticAsset {
|
||||
pub const EXT_JSON_1_19_12: servable::StaticAsset = servable::StaticAsset {
|
||||
bytes: include_str!("../htmx/json-enc-1.9.12.js").as_bytes(),
|
||||
mime: mime::MimeType::Javascript,
|
||||
ttl: StaticAsset::DEFAULT_TTL,
|
||||
};
|
||||
|
||||
@@ -225,6 +225,13 @@ impl<'de> Deserialize<'de> for MimeType {
|
||||
|
||||
impl Default for MimeType {
|
||||
fn default() -> Self {
|
||||
Self::const_default()
|
||||
}
|
||||
}
|
||||
|
||||
impl MimeType {
|
||||
/// [Default::default], but const
|
||||
pub const fn const_default() -> Self {
|
||||
Self::Blob
|
||||
}
|
||||
}
|
||||
|
||||
@@ -35,9 +35,9 @@ impl Servable for Default404 {
|
||||
code: StatusCode::NOT_FOUND,
|
||||
body: (),
|
||||
ttl: Some(TimeDelta::days(1)),
|
||||
immutable: true,
|
||||
headers: HeaderMap::new(),
|
||||
mime: Some(MimeType::Html),
|
||||
private: false,
|
||||
};
|
||||
})
|
||||
}
|
||||
@@ -73,6 +73,7 @@ impl Servable for Default404 {
|
||||
/// StaticAsset {
|
||||
/// bytes: "I am a page".as_bytes(),
|
||||
/// mime: MimeType::Text,
|
||||
/// ttl: StaticAsset::DEFAULT_TTL
|
||||
/// },
|
||||
/// );
|
||||
///
|
||||
@@ -243,14 +244,15 @@ impl Service<Request<Body>> for ServableRouter {
|
||||
// Tweak headers
|
||||
{
|
||||
if !rend.headers.contains_key(header::CACHE_CONTROL) {
|
||||
let max_age = rend.ttl.map(|x| x.num_seconds()).unwrap_or(1).max(1);
|
||||
let max_age = rend.ttl.map(|x| x.num_seconds()).unwrap_or(0).max(0);
|
||||
|
||||
let mut value = String::new();
|
||||
if rend.immutable {
|
||||
value.push_str("immutable, ");
|
||||
}
|
||||
|
||||
value.push_str("public, ");
|
||||
value.push_str(match rend.private {
|
||||
true => "private, ",
|
||||
false => "public, ",
|
||||
});
|
||||
|
||||
value.push_str(&format!("max-age={}, ", max_age));
|
||||
|
||||
#[expect(clippy::unwrap_used)]
|
||||
|
||||
@@ -4,8 +4,6 @@ use std::pin::Pin;
|
||||
|
||||
use crate::{RenderContext, Rendered, RenderedBody, mime::MimeType, servable::Servable};
|
||||
|
||||
const TTL: Option<TimeDelta> = Some(TimeDelta::days(1));
|
||||
|
||||
/// A static blob of bytes
|
||||
pub struct StaticAsset {
|
||||
/// The data to return
|
||||
@@ -13,6 +11,21 @@ pub struct StaticAsset {
|
||||
|
||||
/// The type of `bytes`
|
||||
pub mime: MimeType,
|
||||
|
||||
/// How long to cache this response.
|
||||
/// If None, never cache
|
||||
pub ttl: Option<TimeDelta>,
|
||||
}
|
||||
|
||||
impl StaticAsset {
|
||||
/// Default ttl of a [StaticAsset]
|
||||
pub const DEFAULT_TTL: Option<TimeDelta> = Some(TimeDelta::days(14));
|
||||
|
||||
/// Set `self.ttl`
|
||||
pub const fn with_ttl(mut self, ttl: Option<TimeDelta>) -> Self {
|
||||
self.ttl = ttl;
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "image")]
|
||||
@@ -36,8 +49,8 @@ impl Servable for StaticAsset {
|
||||
return Rendered {
|
||||
code: StatusCode::BAD_REQUEST,
|
||||
body: (),
|
||||
ttl: TTL,
|
||||
immutable: true,
|
||||
ttl: self.ttl,
|
||||
private: false,
|
||||
|
||||
headers: HeaderMap::new(),
|
||||
mime: None,
|
||||
@@ -51,8 +64,8 @@ impl Servable for StaticAsset {
|
||||
return Rendered {
|
||||
code: StatusCode::OK,
|
||||
body: (),
|
||||
ttl: TTL,
|
||||
immutable: true,
|
||||
ttl: self.ttl,
|
||||
private: false,
|
||||
|
||||
headers: HeaderMap::new(),
|
||||
mime: Some(
|
||||
@@ -67,8 +80,8 @@ impl Servable for StaticAsset {
|
||||
return Rendered {
|
||||
code: StatusCode::OK,
|
||||
body: (),
|
||||
ttl: TTL,
|
||||
immutable: true,
|
||||
ttl: self.ttl,
|
||||
private: false,
|
||||
|
||||
headers: HeaderMap::new(),
|
||||
mime: Some(self.mime.clone()),
|
||||
@@ -99,8 +112,8 @@ impl Servable for StaticAsset {
|
||||
return Rendered {
|
||||
code: StatusCode::BAD_REQUEST,
|
||||
body: RenderedBody::String(err),
|
||||
ttl: TTL,
|
||||
immutable: true,
|
||||
ttl: self.ttl,
|
||||
private: false,
|
||||
|
||||
headers: HeaderMap::new(),
|
||||
mime: None,
|
||||
@@ -131,7 +144,7 @@ impl Servable for StaticAsset {
|
||||
"Error while transforming image: {error:?}"
|
||||
)),
|
||||
ttl: None,
|
||||
immutable: true,
|
||||
private: false,
|
||||
|
||||
headers: HeaderMap::new(),
|
||||
mime: None,
|
||||
@@ -144,8 +157,8 @@ impl Servable for StaticAsset {
|
||||
return Rendered {
|
||||
code: StatusCode::OK,
|
||||
body: RenderedBody::Bytes(bytes),
|
||||
ttl: TTL,
|
||||
immutable: true,
|
||||
ttl: self.ttl,
|
||||
private: false,
|
||||
|
||||
headers: HeaderMap::new(),
|
||||
mime: Some(mime),
|
||||
@@ -156,8 +169,8 @@ impl Servable for StaticAsset {
|
||||
return Rendered {
|
||||
code: StatusCode::INTERNAL_SERVER_ERROR,
|
||||
body: RenderedBody::String(format!("{err}")),
|
||||
ttl: TTL,
|
||||
immutable: true,
|
||||
ttl: self.ttl,
|
||||
private: false,
|
||||
|
||||
headers: HeaderMap::new(),
|
||||
mime: None,
|
||||
@@ -170,8 +183,9 @@ impl Servable for StaticAsset {
|
||||
return Rendered {
|
||||
code: StatusCode::OK,
|
||||
body: RenderedBody::Static(self.bytes),
|
||||
ttl: TTL,
|
||||
immutable: true,
|
||||
ttl: self.ttl,
|
||||
private: false,
|
||||
|
||||
headers: HeaderMap::new(),
|
||||
mime: Some(self.mime.clone()),
|
||||
};
|
||||
@@ -191,8 +205,8 @@ impl Servable for StaticAsset {
|
||||
return Rendered {
|
||||
code: StatusCode::OK,
|
||||
body: (),
|
||||
ttl: TTL,
|
||||
immutable: true,
|
||||
ttl: self.ttl,
|
||||
private: false,
|
||||
|
||||
headers: HeaderMap::new(),
|
||||
mime: Some(self.mime.clone()),
|
||||
|
||||
@@ -52,7 +52,7 @@ pub struct HtmlPage {
|
||||
pub meta: PageMetadata,
|
||||
|
||||
/// If true, the contents of this page never change
|
||||
pub immutable: bool,
|
||||
pub private: bool,
|
||||
|
||||
/// How long this page's html may be cached.
|
||||
/// This controls the maximum age of a page shown to the user.
|
||||
@@ -94,7 +94,7 @@ impl Default for HtmlPage {
|
||||
HtmlPage {
|
||||
// No cache by default
|
||||
ttl: None,
|
||||
immutable: false,
|
||||
private: false,
|
||||
|
||||
meta: Default::default(),
|
||||
render: Arc::new(|_, _| Box::pin(async { html!() })),
|
||||
@@ -132,10 +132,10 @@ impl HtmlPage {
|
||||
self
|
||||
}
|
||||
|
||||
/// Set `self.immutable`
|
||||
/// Set `self.private`
|
||||
#[inline(always)]
|
||||
pub fn with_immutable(mut self, immutable: bool) -> Self {
|
||||
self.immutable = immutable;
|
||||
pub fn with_private(mut self, private: bool) -> Self {
|
||||
self.private = private;
|
||||
self
|
||||
}
|
||||
|
||||
@@ -223,7 +223,7 @@ impl Servable for HtmlPage {
|
||||
code: self.response_code,
|
||||
body: (),
|
||||
ttl: self.ttl,
|
||||
immutable: self.immutable,
|
||||
private: self.private,
|
||||
headers: HeaderMap::new(),
|
||||
mime: Some(MimeType::Html),
|
||||
};
|
||||
|
||||
@@ -60,7 +60,7 @@ impl Servable for Redirect {
|
||||
headers,
|
||||
body: (),
|
||||
ttl: None,
|
||||
immutable: true,
|
||||
private: false,
|
||||
mime: None,
|
||||
};
|
||||
})
|
||||
|
||||
@@ -58,8 +58,8 @@ pub struct Rendered<T: RenderedBodyType> {
|
||||
/// If none, don't cache.
|
||||
pub ttl: Option<TimeDelta>,
|
||||
|
||||
/// If true, the data at this route will never change.
|
||||
pub immutable: bool,
|
||||
/// If true, this response sets `Cache-Control: private`
|
||||
pub private: bool,
|
||||
}
|
||||
|
||||
impl Rendered<()> {
|
||||
@@ -71,7 +71,7 @@ impl Rendered<()> {
|
||||
body,
|
||||
mime: self.mime,
|
||||
ttl: self.ttl,
|
||||
immutable: self.immutable,
|
||||
private: self.private,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user