Watcher scope

This commit is contained in:
Daniel Flanagan 2024-05-07 19:49:04 -05:00
parent 28f1f9adb8
commit 2295b7d5ef
2 changed files with 17 additions and 20 deletions

View file

@ -1,10 +1,6 @@
use axum::{serve, Router}; use axum::{serve, Router};
use notify::{Config, RecommendedWatcher, RecursiveMode, Watcher}; use notify::{Config, RecommendedWatcher, RecursiveMode, Watcher};
use std::{ use std::{path::PathBuf, str::FromStr, sync::OnceLock};
path::{Path, PathBuf},
str::FromStr,
sync::OnceLock,
};
use tokio::sync::mpsc::channel; use tokio::sync::mpsc::channel;
use tower_http::services::ServeDir; use tower_http::services::ServeDir;
use tower_livereload::{LiveReloadLayer, Reloader}; use tower_livereload::{LiveReloadLayer, Reloader};
@ -37,26 +33,34 @@ async fn main() -> Besult<()> {
// load configuration? // load configuration?
observe::setup_logging(); observe::setup_logging();
let rl_layer = live_reload_layer()?; // pulling the watcher into main's scope lets it live until the program dies
let (rl_layer, _watcher) = live_reload_layer()?;
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap(); let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
info!("Listening on {listener:#?}"); info!("Listening on {listener:#?}");
Ok(serve(listener, static_files()?.layer(rl_layer)).await?) let router = Router::new()
.nest_service("/static", ServeDir::new(static_file_dir()))
.layer(rl_layer);
Ok(serve(listener, router).await?)
} }
fn live_reload_layer() -> Besult<LiveReloadLayer> { fn live_reload_layer() -> Besult<(LiveReloadLayer, RecommendedWatcher)> {
let rl_layer = LiveReloadLayer::new(); let rl_layer = LiveReloadLayer::new();
let rl = rl_layer.reloader(); let rl = rl_layer.reloader();
static_file_watcher(rl)?; let watcher = static_file_watcher(rl)?;
Ok(rl_layer) Ok((rl_layer, watcher))
} }
fn static_file_watcher(reloader: Reloader) -> Result<(), Box<dyn std::error::Error>> { fn static_file_watcher(
reloader: Reloader,
) -> Result<RecommendedWatcher, Box<dyn std::error::Error>> {
info!("Creating async watcher..."); info!("Creating async watcher...");
let (tx, mut rx) = channel(1); let (tx, mut rx) = channel(1);
info!("Creating watcher..."); info!("Creating watcher...");
// watcher needs to move out of scope to live long enough to watch
let mut watcher = RecommendedWatcher::new( let mut watcher = RecommendedWatcher::new(
move |res| { move |res| {
info!("Res from watcher: {res:#?}"); info!("Res from watcher: {res:#?}");
@ -84,12 +88,5 @@ fn static_file_watcher(reloader: Reloader) -> Result<(), Box<dyn std::error::Err
} }
}); });
Ok(()) Ok(watcher)
}
fn static_files() -> Result<Router, notify::Error> {
let static_file_path = Path::new("./static/");
// serve the file in the "assets" directory under `/assets`
info!("Starting static file server...");
Ok(Router::new().nest_service("/static", ServeDir::new(static_file_path)))
} }

View file

@ -1,2 +1,2 @@
<!DOCTYPE html> <!DOCTYPE html>
Sup Dawgy Sup Dawg