Home > Software design >  How do I serve a static HTML at API endpoint using Rocket?
How do I serve a static HTML at API endpoint using Rocket?

Time:10-04

I want to serve a simple html file as a response to a request to an API endpoint like / or api/ the only thing I have managed to find online is how to host the a static file as /index.html for example.

I am using the rocket crate in Rust.

CodePudding user response:

You can find sth relevant in the Templates in both guides and examples. I think this might be what you need.

CodePudding user response:

You can serve a single file from a route by returning NamedFile:

use rocket::fs::NamedFile;
use rocket::get;

#[get("/api")]
async fn serve_home_page() -> Result<NamedFile, std::io::Error> {
    NamedFile::open("index.html").await
}

This is the 0.5 API; if you're using 0.4 then change the import to rocket::response::NamedFile and remove the async/await syntax. You can also return a simple std::fs::File or tokio::fs::File, but the NamedFile will do the extra step of setting the correct Content-Type header based on the file extension.

  • Related