The first step is to install tokio, our async runtime and the axum web server.
cargo add tokio --features full
cargo add axum
Once we have tokio and axum, we can then create our first route and run it.
use axum::{
routing::get,
Router,
};
async fn index() -> &'static str {
"Hello, World!!!"
}
#[tokio::main]
async fn main() {
let app = Router::new()
.route("/", get(index));
let address = "0.0.0.0:7080";
println!("Listening: {address}");
let listener = tokio::net::TcpListener::bind(&address)
.await
.unwrap();
axum::serve(listener, app)
.await
.unwrap();
}
Now to run it:
cargo run
We should then see the following in our terminal:
Listening: 0.0.0.0:7080
and if we open the page in the browser we should see our "Hello, World!".
Everytime we make a change we will need to stop our server and recompile our application. We can make this easier by using watchexec-cli which will let us recompile and run our axum server everytime something in our src directory changes.
First install watchexec-cli
cargo install watchexec-cli
Once this is installed we can then run:
watchexec -r cargo run
This will run cargo run
everytime our src directory changes.