feat: Add auto-reload on development environment

This commit is contained in:
Simon C 2024-08-08 22:14:11 +02:00
parent 668a91941b
commit 1ae80c161f
5 changed files with 49 additions and 5 deletions

5
.ignore Normal file
View File

@ -0,0 +1,5 @@
# Ignorer les fichiers dont ne dépent pas la compilation
*.md
tailwind.config.js
*.example
scripts

12
Cargo.lock generated
View File

@ -69,6 +69,7 @@ dependencies = [
"askama",
"askama_axum",
"axum",
"listenfd",
"serde",
"tokio",
"tower-http",
@ -1717,6 +1718,17 @@ dependencies = [
"libc",
]
[[package]]
name = "listenfd"
version = "1.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e0500463acd96259d219abb05dc57e5a076ef04b2db9a2112846929b5f174c96"
dependencies = [
"libc",
"uuid",
"winapi",
]
[[package]]
name = "lock_api"
version = "0.4.12"

View File

@ -7,7 +7,7 @@ edition = "2021"
askama = "0.12.1"
askama_axum = "0.4.0"
axum = "0.7.5"
listenfd = "1.0.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"] }

View File

@ -13,3 +13,17 @@
```bash
cargo run --bin app
```
## L'auto-reload
Pour permettre au projet de s'auto-recharger lors du développement, nous avons besoin de 2 librairies :
```bash
cargo install cargo-watch systemfd
```
Pour recompiler automatiquement le serveur lors de changement :
```bash
systemfd --no-pid -s http::3000 -- cargo watch -x 'run --bin app'
```

View File

@ -1,6 +1,8 @@
use ::app::get_router;
use listenfd::ListenFd;
use std::env;
use std::path::Path;
use tokio::net::TcpListener;
#[tokio::main]
async fn main() {
@ -8,10 +10,21 @@ async fn main() {
let assets_path = Path::new(&manifest_dir).join("assets");
let router = get_router(assets_path.as_path());
// TODO: select port based on available port (or ask in CLI)
let listener = tokio::net::TcpListener::bind("localhost:3000")
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(),
};
println!("Listening on: http://{}", listener.local_addr().unwrap());
// Run the server with the router
axum::serve(listener, router.into_make_service())
.await
.unwrap();
println!("Listening on: http://{}", listener.local_addr().unwrap());
axum::serve(listener, router).await.unwrap();
}