我尝试通过 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/