Open2

Rust axum , public フォルダ アクセス SSR , CSR

knaka Tech-Blogknaka Tech-Blog

概要

  • Rust axumの /public のファイル読込設定など。
  • SSR, CSR 例

[ 公開 2025/06/25 ]


関連


環境

  • Rust: cargo 1.83.0
  • Axum
  • tower-http

CSR

https://github.com/kuc-arc-f/axum_1ex/blob/main/csr1/Cargo.toml

[package]
name = "ssr_example"
version = "0.1.0"
edition = "2024"

[dependencies]
axum = "0.7.5"
tokio = { version = "1.0", features = ["full"] }
tower-http = { version = "0.6.6", features = ["fs"] }

  • csr1/src/main.rs

https://github.com/kuc-arc-f/axum_1ex/blob/main/csr1/src/main.rs

  • /foo: index.htm 読み込む、public/ 下の、js読み込む
#[tokio::main]
async fn main() {
    // `public` フォルダのパス
    let public_dir = "public";

    // `ServeDir` ミドルウェアを初期化
    let serve_dir = ServeDir::new(public_dir);
    //.route("/", get(root))
    let app = Router::new()
        .nest_service("/", serve_dir)
        .route("/foo", get(get_foo));

    let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
    axum::serve(listener, app).await.unwrap();
}

async fn root() -> String {
    String::from("root\n")
}

async fn get_foo() -> String {
    String::from("get_foo\n")
}

  • csr1/public/index.html

https://github.com/kuc-arc-f/axum_1ex/blob/main/csr1/public/index.html


  • csr1/public/test.js , レンダリングします。

https://github.com/kuc-arc-f/axum_1ex/blob/main/csr1/public/test.js

knaka Tech-Blogknaka Tech-Blog

SSR , Rust axum

  • SSRの 例になります。

  • ssr1/Cargo.toml

https://github.com/kuc-arc-f/axum_1ex/blob/main/ssr1/Cargo.toml

[package]
name = "ssr_example"
version = "0.1.0"
edition = "2024"

[dependencies]
axum = "0.7.5"
tokio = { version = "1.0", features = ["full"] }
tower-http = { version = "0.6.6", features = ["fs"] }

  • SSR
  • ssr1/src/main.rs
  • /foo の画面を SSRに
  • Htmlに、 html文字を送信すると、表示できました。

https://github.com/kuc-arc-f/axum_1ex/blob/main/ssr1/src/main.rs

#[tokio::main]
async fn main() {
    // `public` フォルダのパス
    let public_dir = "public";

    // `ServeDir` ミドルウェアを初期化
    let serve_dir = ServeDir::new(public_dir);

    let app = Router::new()
        .nest_service("/", serve_dir)
        .route("/foo", get(get_foo));

    let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
    axum::serve(listener, app).await.unwrap();
}

async fn root() -> String {
    String::from("root\n")
}

async fn get_foo() -> Html<&'static str> {
    let s1 = "<html>
  <head>
    <title>welcome</title>
  </head>
  <body>
    <h1>Hello</h1>
    <script type='module' src='/test.js'></script>
  <body>
</html>
";
    Html(&s1)
}