【问题标题】:How can I set the HTTP status code of a (Rust) Rocket API endpoint's Template response?如何设置(Rust)Rocket API 端点的模板响应的 HTTP 状态代码?
【发布时间】:2024-04-11 19:20:03
【问题描述】:

我的 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 以外的值通知浏览器登录成功。

【问题讨论】:

    标签: rust-rocket


    【解决方案1】:

    来自Template docs(特别是响应者特质):

    返回一个响应,其 Content-Type 派生自模板的扩展和一个包含呈现模板的固定大小的正文。如果渲染失败,则返回 Status::InternalServerError 中的 Err

    尝试创建一个新的 Error 枚举来派生 Responder 特征。不要返回Result&lt;Redirect, Template&gt;,而是返回Result&lt;Redirect, Error&gt;,其中Error 看起来像这样:

    #[derive(Debug, Responder)]
    enum Error {
        #[response(status = 400)]
        BadRequest(Template),
        #[response(status = 404)]
        NotFound(Template),
    }
    

    【讨论】:

      最近更新 更多