Description

This example has one route at / where the homepage is served and shows you how you can serve HTML or other types of files with Actix Web.

Note that static assets are declared in the Shuttle.toml file.

You can clone the example below by running the following (you’ll need cargo-shuttle installed):

cargo shuttle init --from shuttle-hq/shuttle-examples \
 --subfolder rocket/static-files

Code

use rocket::fs::NamedFile;
use rocket::fs::{relative};
use std::path::{Path, PathBuf};

#[rocket::get("/<path..>")]
pub async fn serve(mut path: PathBuf) -> Option<NamedFile> {
    path.set_extension("html");
    let mut path = Path::new(relative!("assets")).join(path);
    if path.is_dir() {
        path.push("index.html");
    }

    NamedFile::open(path).await.ok()
}

#[shuttle_runtime::main]
async fn rocket() -> shuttle_rocket::ShuttleRocket {
    let rocket = rocket::build().mount("/", rocket::routes![serve]);

    Ok(rocket.into())
}

Usage

After you clone the example, launch it locally by using cargo shuttle run then visit the home route at http://localhost:8000 - you should see a homepage that shows our included HTML file.

You can extend this example by adding more routes that serve other files.


If you want to explore other frameworks, we have more examples with popular ones like Tower and Warp. You can find them right here.

Be sure to check out the examples repo for many more examples!