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.
Thanks for any help I'm new to web related programming so my terminology might have sucked. I really tried finding anything related.
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.