TheEyeOfAr3s
TheEyeOfAr3s

Reputation: 128

How do I serve a static HTML at API endpoint using Rocket?

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.

Upvotes: 0

Views: 1264

Answers (2)

kmdreko
kmdreko

Reputation: 59882

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.

Upvotes: 1

BobAnkh
BobAnkh

Reputation: 591

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

Upvotes: 0

Related Questions