【Rust】axumを使いたい

### hello world

[dependencies]
axum = "0.7.1"
serde = { version = "1.0.193", features = ["derive"]}
tera = "1.19.1"
tokio = { version = "1.34.0", features = ["full"] }
use axum::{Router, routing::get};

#[tokio::main]
async fn main() {
    let app = Router::new().route("/", get(|| async {
        "hello world"
    }));
    let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
    axum::serve(listener, app).await.unwrap();
}

http://192.168.33.10:3000/
hello world

### templateの利用
templates/index.html

hello {{ name }}!
use axum::{Router, response::Html, routing::get};
use tera::{Context, Tera};
use serde::Serialize;

#[derive(Serialize)]
struct Index {
    name: String
}

#[tokio::main]
async fn main() {
    let tera = match Tera::new("templates/**/*.html"){
        Ok(t) => t,
        Err(e) => {
            println!("Parsing error(s): {}", e);
            ::std::process::exit(1);
        }
    };

    let index = Index { name: String::from("test") };
    let page = tera.render("index.html", &Context::from_serialize(&index).unwrap()).unwrap();

    let app = Router::new().route("/", get(|| async move {
        Html(page.to_owned())
    }));
    let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
    axum::serve(listener, app).await.unwrap();
}

### with_state

use axum::{Router, extract::State, response::Html, routing::get};
use tera::{Context, Tera};
use serde::Serialize;

#[derive(Serialize)]
struct Index {
    name: String
}

#[derive(Clone)]
struct ServiceState {
    tera: Tera,
}

async fn index(State(state): State<ServiceState>) -> Html<String> {
    let index = Index { name: String::from("test") };
    let page = state.tera.render("index.html", &Context::from_serialize(&index).unwrap()).unwrap();
    Html(page.to_owned())
}

#[tokio::main]
async fn main() {
    let tera = match Tera::new("templates/**/*.html"){
        Ok(t) => t,
        Err(e) => {
            println!("Parsing error(s): {}", e);
            ::std::process::exit(1);
        }
    };

    
    let app = Router::new()
        .route("/", get(index))
        .with_state(ServiceState {tera});
    let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
    axum::serve(listener, app).await.unwrap();
}