Search code examples
jsonrustbackendrust-axum

Server side rendering with Axum-rust


I'm just trying to make a very basic web app using Axum and rust as a back end. I've only used express js which uses server side rendering. I want to do something similar in Axum but I'm confused on how exactly to do it. I know that I can send JSON information but what if I want to send a full html file? Is this possible in Axum?

I've looked for how most people send data to the front end and I've seen nothing about sending html files. I've mostly just seen data sent in the form of JSON.


Solution

  • Yes it's definitely possible to do that, but I prefer to use a template engine to do this kind of tasks. Anyway, you can start from the basic "hello world" example that you can can find here and make some simple changes.

    use axum::{response::Html, routing::get, Router};
    use std::path::Path;
    use tokio::fs::File;
    use tokio::io::{self, AsyncReadExt};
    
    #[tokio::main]
    async fn main() {
        // build our application with a route
        let app = Router::new().route("/", get(handler));
    
        // run it
        let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
            .await
            .unwrap();
        println!("listening on {}", listener.local_addr().unwrap());
        axum::serve(listener, app).await.unwrap();
    }
    
    async fn handler() -> Html<String> {
        let html_content = 
        read_html_from_file("index.html").await.unwrap_or_else(|_| {
            "<h1>Error loading HTML file</h1>".to_string()
        });
        Html(html_content)
    }
    
    async fn read_html_from_file<P: AsRef<Path>>(path: P) -> io::Result<String> {
        let mut file = File::open(path).await?;
        let mut contents = String::new();
        file.read_to_string(&mut contents).await?;
        Ok(contents)
    }
    

    Now, you can simply create an html file and place it the same folder where your main.rs is.