rust - 状态代码和 header 在 actix web 中不起作用

标签 rust actix-web

我尝试通过 HTTPResponseBuilder 返回响应,但即使我使用自定义 status_code(如 307)和 Location: google.com header ,我的浏览器也不会将我重定向到同一网站。

这是我使用的示例代码:

    let mut response = HttpResponse::Ok();
    let status_code =
        actix_http::StatusCode::from_str(contents.get("status_code").unwrap()).unwrap();
    apply_headers(&mut response, headers[0].clone());
    response.status(status_code);
    println!(
        "The status code is {} and the headers are {:?}",
        status_code, headers
    );
    response.body(contents.get("body").unwrap().to_owned())

我可以分享整个 PR,但在我看来这是相关部分。

最佳答案

对我来说效果很好

use actix_web::http::header::HeaderValue;
use actix_web::http::{header, StatusCode};
use actix_web::{get, App, HttpResponse, HttpServer, Responder};

#[get("/")]
async fn redirect() -> impl Responder {
    let mut response = HttpResponse::Ok();
    response.status(StatusCode::TEMPORARY_REDIRECT); // mimic your dynamic example
    response.append_header((
        header::LOCATION,
        HeaderValue::from_static("https://www.google.com"),
    ));
    response
}

#[actix_web::main]
async fn main() -> std::io::Result<()> {
    HttpServer::new(|| App::new().service(redirect))
        .bind(("127.0.0.1", 8080))?
        .run()
        .await
}

根据您在 Location header 中输入的内容,您最终可能会得到绝对或相对 URL。例如。 www.google.com 会将您重定向到 http://localhost:8080/www.google.com。 还要确保客户端遵循重定向,这通常是一个单独的设置。

关于rust - 状态代码和 header 在 actix web 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71445950/

相关文章:

multithreading - 除scoped_threshhold外的Rust处理变量

types - 如何匹配泛型参数的具体类型?

rust - 我可以编写一个使自己变异然后生成对自身的引用的Iterator吗?

rust - 如何在 actix-web 提取器中使用异步代码?

rust - Actix-Web 中如何获取 IP 地址进行限速?

rust - Cargo 安装的模块存储在 Rust 项目中的什么位置?

rust - 如何在Rust中找到本地时区偏移量?

asynchronous - 如何在 Actix-web 中的 WebSocket 处理程序中正确调用异步函数

rust - 如何将JSON模式作为数据传递给Actix Web?

rust - 如何在 Actix-web 4.0 中使用 actix_web::client::Client