refacto: extract TCP Listener building into a dedicated function

Co-authored-by: kosssi <github@fafaru.com>
This commit is contained in:
Florian Briand 2024-08-09 12:27:31 +02:00
parent 0c8e417f11
commit dcb4a7680e
Signed by: florian_briand
GPG Key ID: CC981B9E6B98E70B

View File

@ -7,40 +7,45 @@ use std::path::Path;
use tokio::net::TcpListener;
use tower_livereload::LiveReloadLayer;
// Nous filtrons les requêtes de `htmx` pour ne pas inclure le script _JS_ qui gère le rechargement
// Voir https://github.com/leotaku/tower-livereload/pull/3
/// Nous filtrons les requêtes de `htmx` pour ne pas inclure le script _JS_ qui gère le rechargement
/// Voir https://github.com/leotaku/tower-livereload/pull/3
fn not_htmx_predicate<T>(req: &Request<T>) -> bool {
!req.headers().contains_key("hx-request")
}
const DEFAULT_LISTENER: &str = "localhost:3000";
async fn get_tcp_listener() -> TcpListener {
let mut listenfd = ListenFd::from_env();
match listenfd.take_tcp_listener(0).unwrap() {
// if we are given a tcp listener on listen fd 0, we use that one
Some(listener) => {
listener.set_nonblocking(true).unwrap();
TcpListener::from_std(listener).unwrap()
}
// otherwise fall back to local listening
None => TcpListener::bind(DEFAULT_LISTENER).await.unwrap(),
}
}
#[tokio::main]
async fn main() {
let manifest_dir = env::var("CARGO_MANIFEST_DIR").unwrap();
let assets_path = Path::new(&manifest_dir).join("assets");
let templates_path = Path::new(&manifest_dir).join("templates");
// Setup the livereload
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() {
// if we are given a tcp listener on listen fd 0, we use that one
Some(listener) => {
listener.set_nonblocking(true).unwrap();
TcpListener::from_std(listener).unwrap()
}
// otherwise fall back to local listening
None => TcpListener::bind("localhost:3000").await.unwrap(),
};
let router =
get_router(assets_path.as_path()).layer(livereload.request_predicate(not_htmx_predicate));
let listener: TcpListener = get_tcp_listener().await;
println!("Listening on: http://{}", listener.local_addr().unwrap());
// Run the server with the router