mirror of
https://github.com/tokio-rs/axum.git
synced 2025-04-26 13:56:22 +02:00
Add auto-reload example (#2166)
This commit is contained in:
parent
998ef8dc89
commit
3f5c907e2d
3 changed files with 59 additions and 0 deletions
examples/auto-reload
10
examples/auto-reload/Cargo.toml
Normal file
10
examples/auto-reload/Cargo.toml
Normal file
|
@ -0,0 +1,10 @@
|
|||
[package]
|
||||
name = "auto-reload"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
publish = false
|
||||
|
||||
[dependencies]
|
||||
axum = { path = "../../axum" }
|
||||
listenfd = "1.0.1"
|
||||
tokio = { version = "1.0", features = ["full"] }
|
18
examples/auto-reload/README.md
Normal file
18
examples/auto-reload/README.md
Normal file
|
@ -0,0 +1,18 @@
|
|||
# auto-reload
|
||||
|
||||
This example shows how you can set up a development environment for your axum
|
||||
service such that whenever the source code changes, the app is recompiled and
|
||||
restarted. It uses `listenfd` to be able to migrate connections from an old
|
||||
version of the app to a newly-compiled version.
|
||||
|
||||
## Setup
|
||||
|
||||
```sh
|
||||
cargo install cargo-watch systemfd
|
||||
```
|
||||
|
||||
## Running
|
||||
|
||||
```sh
|
||||
systemfd --no-pid -s http::3000 -- cargo watch -x run
|
||||
```
|
31
examples/auto-reload/src/main.rs
Normal file
31
examples/auto-reload/src/main.rs
Normal file
|
@ -0,0 +1,31 @@
|
|||
//! Run with
|
||||
//!
|
||||
//! ```not_rust
|
||||
//! cargo run -p example-hello-world
|
||||
//! ```
|
||||
|
||||
use axum::{response::Html, routing::get, Router};
|
||||
use listenfd::ListenFd;
|
||||
use tokio::net::TcpListener;
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() {
|
||||
// build our application with a route
|
||||
let app = Router::new().route("/", get(handler));
|
||||
|
||||
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) => TcpListener::from_std(listener).unwrap(),
|
||||
// otherwise fall back to local listening
|
||||
None => TcpListener::bind("127.0.0.1:3000").await.unwrap(),
|
||||
};
|
||||
|
||||
// run it
|
||||
println!("listening on {}", listener.local_addr().unwrap());
|
||||
axum::serve(listener, app).await.unwrap();
|
||||
}
|
||||
|
||||
async fn handler() -> Html<&'static str> {
|
||||
Html("<h1>Hello, World!</h1>")
|
||||
}
|
Loading…
Add table
Reference in a new issue