feat: Add livereload

This commit is contained in:
Simon C
2024-08-07 23:50:25 +02:00
parent 4a54846f47
commit c342d922a7
3 changed files with 139 additions and 5 deletions

View File

@ -8,7 +8,9 @@ askama = "0.12.1"
askama_axum = "0.4.0"
axum = "0.7.5"
listenfd = "1.0.1"
notify = "6.1.1"
serde = { version = "1.0.204", features = ["derive"] }
tokio = { version = "1.39.1", features = ["macros", "rt-multi-thread"] }
tower-http = { version = "0.5.2", features = ["fs"] }
tower-livereload = "0.9.3"

View File

@ -1,14 +1,29 @@
use ::app::get_router;
use axum::http::Request;
use notify::Watcher;
use std::env;
use std::path::Path;
use listenfd::ListenFd;
use tokio::net::TcpListener;
use tower_livereload::LiveReloadLayer;
fn not_htmx_predicate<T>(req: &Request<T>) -> bool {
!req.headers().contains_key("hx-request")
}
#[tokio::main]
async fn main() {
let manifest_dir = env::var("CARGO_MANIFEST_DIR").unwrap();
let assets_path = Path::new(&manifest_dir).join("assets");
let router = get_router(assets_path.as_path());
let templates_path = Path::new(&manifest_dir).join("templates");
let livereload = LiveReloadLayer::new();
let reloader = livereload.reloader();
let router = get_router(assets_path.as_path()).layer(livereload.request_predicate(not_htmx_predicate));
let mut watcher = notify::recommended_watcher(move |_| reloader.reload()).unwrap();
watcher.watch(&templates_path, notify::RecursiveMode::Recursive).unwrap();
let mut listenfd = ListenFd::from_env();
let listener = match listenfd.take_tcp_listener(0).unwrap() {
@ -18,7 +33,7 @@ async fn main() {
TcpListener::from_std(listener).unwrap()
}
// otherwise fall back to local listening
None => TcpListener::bind("127.0.0.1:3000").await.unwrap(),
None => TcpListener::bind("localhost:3000").await.unwrap(),
};
println!("Listening on: http://{}", listener.local_addr().unwrap());