Thursday | 21 NOV 2024
[ previous ]
[ next ]

Axum Tutorial

Title:
Date: 2024-11-11
Tags:  

  • 01 - Hello World
  • 02 - Creating the Register Page
  • 03 - Getting the Data
  • 04 - Creating a User using sqlx
  • 05 - Creating the Login Page
  • 06 - Sessions

Chapter 1 - Hello, World

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!".

Chapter 1.5 - Using watchexec

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.