2

I am trying to return a response via the HTTPResponseBuilder but even when I am using a custom status_code say 307 and a header of Location: google.com, my browser is not redirecting me to the same website.

Here is the sample code that I using:

    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())

I can share the entire PR but this is the relevant part IMO.

Sanskar Jethi
  • 544
  • 5
  • 17

1 Answers1

2

Works perfectly fine for me with

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
}

Depending on the content you put in the Location header, you might end up with a absolute or relative url. E.g. www.google.com will redirect you to http://localhost:8080/www.google.com. Also make sure the client follows redirects, which is often a separate setting.

peterulb
  • 2,869
  • 13
  • 20
  • Thank you for the response but the issue was something else. I was passing some content every time. This is how I got to know that the browser always prioritises Content-Length over status-code and Location headers. – Sanskar Jethi Mar 14 '22 at 11:45