Hello.
I am kinda new to Rust and I am using Rocket to write a simple server. I want the request to the homepage would redirect to the login page if there is no auth token in Cookie.
So here is my code:
#[get("/login")]
async fn login() -> Option<NamedFile> {
NamedFile::open("static/login.html").await.ok()
}
#[get("/")]
async fn index(cookies: &CookieJar<'_>) -> Option<NamedFile> {
match auth::auth(&cookies).await {
Ok(_) =>{
NamedFile::open("static/index.html").await.ok()
}
Err(_) => {
// Redirect::to(uri!(login));
// NamedFile::open("static/login.html").await.ok()
login().await
}
}
}
Nothing fancy really, but I just want to know what is the correct way to do the redirect to login page action.
I have 3 options:
- Call the function
login()
from functionindex()
, which is what I am doing. - Serve that
login.html
file directly within theindex()
function. - Redirect to
/login
I am using 1 because if I tried (3), I code would not run, as I believes it expect me to return an Option with Redirect::to(uri!(login))
, but the function return Option<NamedFile>
.
So, my questions are, in the three above ways to solve this problem:
- What is the most elegant solution in general, or at least the most "Rustic" way?
- Suppose I want to do (3), what should I do with the return type of
function index()
?
Thank you.