From 2295b7d5ef1d99cffd6cfb65f0930643e86d0fb2 Mon Sep 17 00:00:00 2001 From: Daniel Flanagan Date: Tue, 7 May 2024 19:49:04 -0500 Subject: [PATCH] Watcher scope --- src/main.rs | 35 ++++++++++++++++------------------- static/index.html | 2 +- 2 files changed, 17 insertions(+), 20 deletions(-) diff --git a/src/main.rs b/src/main.rs index 5853b46..43ea837 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,10 +1,6 @@ use axum::{serve, Router}; use notify::{Config, RecommendedWatcher, RecursiveMode, Watcher}; -use std::{ - path::{Path, PathBuf}, - str::FromStr, - sync::OnceLock, -}; +use std::{path::PathBuf, str::FromStr, sync::OnceLock}; use tokio::sync::mpsc::channel; use tower_http::services::ServeDir; use tower_livereload::{LiveReloadLayer, Reloader}; @@ -37,26 +33,34 @@ async fn main() -> Besult<()> { // load configuration? 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(); 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 { +fn live_reload_layer() -> Besult<(LiveReloadLayer, RecommendedWatcher)> { let rl_layer = LiveReloadLayer::new(); let rl = rl_layer.reloader(); - static_file_watcher(rl)?; - Ok(rl_layer) + let watcher = static_file_watcher(rl)?; + Ok((rl_layer, watcher)) } -fn static_file_watcher(reloader: Reloader) -> Result<(), Box> { +fn static_file_watcher( + reloader: Reloader, +) -> Result> { info!("Creating async watcher..."); let (tx, mut rx) = channel(1); info!("Creating watcher..."); + // watcher needs to move out of scope to live long enough to watch let mut watcher = RecommendedWatcher::new( move |res| { info!("Res from watcher: {res:#?}"); @@ -84,12 +88,5 @@ fn static_file_watcher(reloader: Reloader) -> Result<(), Box Result { - 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))) + Ok(watcher) } diff --git a/static/index.html b/static/index.html index ee0791c..834bdd7 100644 --- a/static/index.html +++ b/static/index.html @@ -1,2 +1,2 @@ -Sup Dawgy +Sup Dawg