如何设置 (Rust) Rocket API 端点模板响应的 HTTP 状态代码?
How can I set the HTTP status code of a (Rust) Rocket API endpoint's Template response?
我的 Rocket API 中有以下登录 POST 端点处理程序:
#[post("/login", data = "<login_form>")]
pub fn login_validate(login_form: Form<LoginForm>) -> Result<Redirect, Template> {
let user = get_user(&login_form.username).unwrap();
match user {
Some(existing_user) => if verify(&login_form.password, &existing_user.password_hash).unwrap() {
return Ok(Redirect::to(uri!(home)))
},
// we now hash (without verifying) just to ensure that the timing is the same
None => {
hash(&login_form.password, DEFAULT_COST);
},
};
let mut response = Template::render("login", &LoginContext {
error: Some(String::from("Invalid username or password!")),
});
// TODO: <<<<<<<<<< HOW CAN I SET AN HTTP STATUS CODE TO THE RESPONSE?
Err(response)
}
我正在尝试设置 HTTP 状态响应代码,但找不到正确的方法?最好通知浏览器登录 未 成功,而不是 200。
来自Template docs(特别是响应者特征):
Returns a response with the Content-Type derived from the template's extension and a fixed-size body containing the rendered template. If rendering fails, an Err
of Status::InternalServerError
is returned.
尝试创建一个新的 Error
枚举来派生 Responder 特征。而不是 returning Result<Redirect, Template>
,return Result<Redirect, Error>
其中 Error
看起来像这样:
#[derive(Debug, Responder)]
enum Error {
#[response(status = 400)]
BadRequest(Template),
#[response(status = 404)]
NotFound(Template),
}
我的 Rocket API 中有以下登录 POST 端点处理程序:
#[post("/login", data = "<login_form>")]
pub fn login_validate(login_form: Form<LoginForm>) -> Result<Redirect, Template> {
let user = get_user(&login_form.username).unwrap();
match user {
Some(existing_user) => if verify(&login_form.password, &existing_user.password_hash).unwrap() {
return Ok(Redirect::to(uri!(home)))
},
// we now hash (without verifying) just to ensure that the timing is the same
None => {
hash(&login_form.password, DEFAULT_COST);
},
};
let mut response = Template::render("login", &LoginContext {
error: Some(String::from("Invalid username or password!")),
});
// TODO: <<<<<<<<<< HOW CAN I SET AN HTTP STATUS CODE TO THE RESPONSE?
Err(response)
}
我正在尝试设置 HTTP 状态响应代码,但找不到正确的方法?最好通知浏览器登录 未 成功,而不是 200。
来自Template docs(特别是响应者特征):
Returns a response with the Content-Type derived from the template's extension and a fixed-size body containing the rendered template. If rendering fails, an
Err
ofStatus::InternalServerError
is returned.
尝试创建一个新的 Error
枚举来派生 Responder 特征。而不是 returning Result<Redirect, Template>
,return Result<Redirect, Error>
其中 Error
看起来像这样:
#[derive(Debug, Responder)]
enum Error {
#[response(status = 400)]
BadRequest(Template),
#[response(status = 404)]
NotFound(Template),
}