Serve A Hello, World Web Page In Rust With axum
Creating a rust server app with a single hard coded web page doesn't require much code at all.
[package]
name = "axum_hello_world"
version = "0.1.0"
edition = "2021"
[dependencies]
tokio = {version = "1", features = ["full"] }
axum = "0.6"
use axum::response::IntoResponse;
use axum::routing::get;
use axum::{response::Html, Router};
use std::net::SocketAddr;
#[tokio::main]
async fn main() {
let index_route = Router::new().route("/", get(index_handler));
let addr = SocketAddr::from(([127, 0, 0, 1], 8181));
axum::Server::bind(&addr)
.serve(index_route.into_make_service())
.await
.unwrap();
}
async fn index_handler() -> impl IntoResponse {
println!("Got request for /");
Html("Hello, world")
}
-
Using "macros,rt-multi-thread" in place of "full" in the tokio dependency works as well. I don't know enough about the difference yet. I went with "full" figuring it'll cover anything else I want to do moving forward and I can roll back as I learn more about it.
-
The example can be made even shorter by including the route direct in the `Router::new()`` chain. Splitting it out is more useful as a general practice. The same goes for the handler which could be called as a closure in `get()``. Again, that is less useful when it comes to practicality.
-
The first time running the cargo commands there won't be any response for a bit as cargo downloads and compiles everything behind the `-q`` quiet flag. The same thing can happen after changes. Removing the `-q`` flag shows all the progress at the expense of more noise in the output. There's no functional difference though.